How to apply LiveData to xxxFragment.class instead of XML - android

How to apply live data isRefreshing to swiperefreshLayout.isRefresh?
Code in xxxViewModel.class:
var isRefreshing = MutableLiveData<Boolean>()
fun refresh() {
viewModelScope.launch(Dispatchers.Main) {
isRefreshing.value = true
withContext(Dispatchers.IO) {
fun doInBackground() // takes a long time
}
isRefreshing.value = false
}
}
Code in xxxFragment.class:
binding.swiperefreshLayout.setOnRefreshListener {
xxxViewModel.refresh()
}
// error here, require Boolean, found MutableLiveData<Boolean>
binding.swiperefreshLayout.isRefreshing = xxxViewModel.isRefreshing
Usually I apply the live data to XML like below, but I cannot find swiperefreshlayout.isRefreshing in XML.
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
isFreshing = "#{xxxViewModel.isRefreshing}">

What you did is to get the current value of the liveData "isRefreshing". (also you need to add .value to get the underlying value associated with the liveData)
binding.swiperefreshLayout.isRefreshing = xxxViewModel.isRefreshing.value?:false
Instead, you should observe the Live Data for changes after initializing your view model.
xxxViewModel.apply {
isRefreshing.observe(viewLifecycleOwner){
binding.swiperefreshLayout.isRefreshing = it
}
//... observe the rest of your LiveData
}
EDIT:
you can create a function like the following
private inline fun <T> doObserve(ld: LiveData<T>, crossinline callback: (T) -> Unit) {
ld.observe(viewLifecycleOwner, { callback.invoke(it) })
}
then just call that instead
xxxViewModel.apply {
doObserve( isRefreshing){
binding.swiperefreshLayout.isRefreshing = it
}
//... observe the rest of your LiveData
}

Related

Kotlin KMM stop coroutine flow with infinite loop properly

I'm building a KMM app for retrieving news.
My app fetches news every 30 seconds and save it in a local database. User must be logged for use it. When user want to logout i need to stop refreshing news and delete the local database.
How do i stop a flow with an infinite loop properly without use static variabile?
I designed the app like follows:
ViewModel (separate for Android and iOS)
UseCase (shared)
Repository (shared)
Data source (shared)
Android Jetpack compose single activity
iOS SwiftUI
Android ViewModel:(iOS use ObservableObject, but logic is the same)
#HiltViewModel
class NewsViewModel #Inject constructor(
private val startFetchingNews: GetNewsUseCase,
private val stopFetchingNews: StopGettingNewsUseCase,
) : ViewModel() {
private val _mutableNewsUiState = MutableStateFlow(NewsState())
val newsUiState: StateFlow<NewsState> get() = _mutableNewsUiState.asStateFlow()
fun onTriggerEvent(action: MapEvents) {
when (action) {
is NewsEvent.GetNews -> {
getNews()
}
is MapEvents.StopNews -> {
//????
}
else -> {
}
}
}
private fun getNews()() {
startFetchingNews().collectCommon(viewModelScope) { result ->
when {
result.error -> {
//update state
}
result.succeeded -> {
//update state
}
}
}
}
}
UseCase:
class GetNewsUseCase(
private val newsRepo: NewsRepoInterface) {
companion object {
private val UPDATE_INTERVAL = 30.seconds
}
operator fun invoke(): CommonFlow<Result<List<News>>> = flow {
while (true) {
emit(Result.loading())
val result = newsRepo.getNews()
if (result.succeeded) {
// emit result
} else {
//emit error
}
delay(UPDATE_INTERVAL)
}
}.asCommonFlow()
}
Repository:
class NewsRepository(
private val sourceNews: SourceNews,
private val cacheNews: CacheNews) : NewsRepoInterface {
override suspend fun getNews(): Result<List<News>> {
val news = sourceNews.fetchNews()
//.....
cacheNews.insert(news) //could be a lot of news
return Result.data(cacheNews.selectAll())
}
}
Flow extension functions:
fun <T> Flow<T>.asCommonFlow(): CommonFlow<T> = CommonFlow(this)
class CommonFlow<T>(private val origin: Flow<T>) : Flow<T> by origin {
fun collectCommon(
coroutineScope: CoroutineScope? = null, // 'viewModelScope' on Android and 'nil' on iOS
callback: (T) -> Unit, // callback on each emission
) {
onEach {
callback(it)
}.launchIn(coroutineScope ?: CoroutineScope(Dispatchers.Main))
}
}
I tried to move the while loop inside repository, so maybe i can break the loop with a singleton repository, but then i must change the getNews method to flow and collect inside GetNewsUseCase (so a flow inside another flow).
Thanks for helping!
When you call launchIn on a Flow, it returns a Job. Hang on to a reference to this Job in a property, and you can call cancel() on it when you want to stop collecting it.
I don't see the point of the CommonFlow class. You could simply write collectCommon as an extension function of Flow directly.
fun <T> Flow<T>.collectCommon(
coroutineScope: CoroutineScope? = null, // 'viewModelScope' on Android and 'nil' on iOS
callback: (T) -> Unit, // callback on each emission
): Job {
return onEach {
callback(it)
}.launchIn(coroutineScope ?: CoroutineScope(Dispatchers.Main))
}
// ...
private var fetchNewsJob: Job? = null
private fun getNews()() {
fetchNewsJob = startFetchingNews().collectCommon(viewModelScope) { result ->
when {
result.error -> {
//update state
}
result.succeeded -> {
//update state
}
}
}
}
In my opinion, collectCommon should be eliminated entirely because all it does is obfuscate your code a little bit. It saves only one line of code at the expense of clarity. It's kind of an antipattern to create a CoroutineScope whose reference you do not keep so you can manage the coroutines running in it--might as well use GlobalScope instead to be clear you don't intend to manage the scope lifecycle so it becomes clear you must manually cancel the Job, not just in the case of the news source change, but also when the UI it's associated with goes out of scope.

End flow/coroutines task before go further null issue

Fragment
private fun makeApiRequest() {
vm.getRandomPicture()
var pictureElement = vm.setRandomPicture()
GlobalScope.launch(Dispatchers.Main) {
// what about internet
if (pictureElement != null && pictureElement!!.fileSizeBytes!! < 400000) {
Glide.with(requireContext()).load(pictureElement!!.url)
.into(layout.ivRandomPicture)
layout.ivRandomPicture.visibility = View.VISIBLE
} else {
getRandomPicture()
}
}
}
viewmodel
fun getRandomPicture() {
viewModelScope.launch {
getRandomPictureItemUseCase.build(Unit).collect {
pictureElement.value = it
Log.d("inspirationquotes", "VIEWMODEL $pictureElement")
Log.d("inspirationquotes", "VIEWMODEL VALUE ${pictureElement.value}")
}
}
}
fun setRandomPicture(): InspirationQuotesDetailsResponse? {
return pictureElement.value
}
Flow UseCase
class GetRandomPictureItemUseCase #Inject constructor(private val api: InspirationQuotesApi): BaseFlowUseCase<Unit, InspirationQuotesDetailsResponse>() {
override fun create(params: Unit): Flow<InspirationQuotesDetailsResponse> {
return flow{
emit(api.getRandomPicture())
}
}
}
My flow task from viewmodel doesn't goes on time. I do not know how to achieve smooth downloading data from Api and provide it further.
I was reading I could use runBlocking, but it is not recommended in production as well.
What do you use in your professional applications to achieve nice app?
Now the effect is that that image doesn't load or I have null error beacause of my Log.d before GlobalScope in Fragment (it is not in code right now).
One more thing is definding null object I do not like it, what do you think?
var pictureElement = MutableStateFlow<InspirationQuotesDetailsResponse?>(null)
EDIT:
Viewmodel
val randomPicture: Flow<InspirationQuotesDetailsResponse> = getRandomPictureItemUseCase.build(Unit)
fragment
private fun makeApiRequest() = lifecycleScope.launch {
vm.randomPicture
.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
.collect { response ->
if (response.fileSizeBytes < 600000) {
Log.d("fragment", "itGetsValue")
Glide.with(requireContext()).load(response.url)
.into(layout.ivRandomPicture)
layout.ivRandomPicture.visibility = View.VISIBLE
} else {
onFloatingActionClick()
}
}
}
Edit2 problem on production, another topic:
Link -> What is the substitute for runBlocking Coroutines in fragments and activities?
First of all, don't use GlobalScope to launch a coroutine, it is highly discouraged and prone to bugs. Use provided lifecycleScope in Fragment:
lifecycleScope.launch {...}
Use MutableSharedFlow instead of MutableStateFlow, MutableSharedFlow doesn't require initial value, and you can get rid of nullable generic type:
val pictureElement = MutableSharedFlow<InspirationQuotesDetailsResponse>()
But I guess we can get rid of it.
Method create() in GetRandomPictureItemUseCase returns a Flow that emits only one value, does it really need to be Flow, or it can be just a simple suspend function?
Assuming we stick to Flow in GetRandomPictureItemUseCase class, ViewModel can look something like the following:
val randomPicture: Flow<InspirationQuotesDetailsResponse> = getRandomPictureItemUseCase.build(Unit)
And in the Fragment:
private fun makeApiRequest() = lifecycleScope.launch {
vm.randomPicture
.flowWithLifecycle(lifecycle, State.STARTED)
.collect { response ->
// .. use response
}
}
Dependency to use lifecycleScope:
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'

How to return a value from a coroutine from a method that is non suspending?

What I've tried so far
fun getCPByID(ids: List<Int>): List<CheckingPointVo> {
var list : List<CheckingPointVo> = emptyList()
coroutineScope.launch {
list = someMethod()
}
return list
}
here I tried to use async and await but that cannot be run from a non suspend function. Is there a way to do this ?
Not really with the current structure, you're basically trying to combine synchronous code with async.
You have 3 possible options though to make it async:
Use a callback:
fun getCPByID(ids: List<Int>, listCallback: (List<CheckingPointVo>) -> Unit) {
coroutineScope.launch {
listCallback(someMethod())
}
}
Note: If you're using it from Java, this should work with either Java lambdas or Function. But you may create an interface for this, like :
Interface ListCallback {
fun onListReceived(list: List<CheckingPointVo>)
}
fun getCPByID(ids: List<Int>, listCallback: ListCallback) {
.... // Same implementation
}
// Call it from Java
getCPByID(ids, new ListCallback() {
void onListReceived(List<CheckingPointVo> list) {
...
}
});
Use either an observable pattern, use a Flow or LiveData. A possible example:
fun getCPByID(ids: List<Int>) = coroutineScope.launch {
flow {
emit(someMethod())
}
}
}
Make your function a suspend function and use coroutineScope.launch from the caller

How change MutableLiveData value inside ViewModel

I need to change the value of MutableLiveData in my ViewModel, but I can't make it because the value is equal to null, I think need to establish an observer change it inside that, but I don't know how to do it and whether it's a good idea.
AudioRecordersListViewModel
class AudioRecordersListViewModel() : ViewModel() {
var audioRecordsLiveData: MutableLiveData<MutableList<AudioRecordUI>> = MutableLiveData();
private var audioRecordDao: AudioRecordDao? = null
#Inject
constructor(audioRecordDao: AudioRecordDao) : this() {
this.audioRecordDao = audioRecordDao
viewModelScope.launch {
val liveDataItems = audioRecordDao
.getAll().value!!.map { item -> AudioRecordUI(item) }
.toMutableList()
if (liveDataItems.size > 0) {
liveDataItems[0].isActive = true
}
audioRecordsLiveData.postValue(liveDataItems)
}
}
}
AudioRecordDao
#Dao
interface AudioRecordDao {
#Query("SELECT * FROM AudioRecordEmpty")
fun getAll(): LiveData<MutableList<AudioRecordEmpty>>
}
First of all, using !! is not a good idea it can easily lead to NullPointer Exception, us ? instead.
You can set an empty list on your LiveData and add new data to that List:
var audioRecordsLiveData: MutableLiveData<MutableList<AudioRecordUI>> = MutableLiveData();
init {
audioRecordsLiveData.value = mutableListOf()
}
If you need to observe that LiveData:
mViewModel.mLiveData.observe(this, Observer { list ->
if (list.isNotEmpty()) {
//Update UI Stuff
}
})
never set your LiveData inside Fragment/Activity
If you need to update your LiveData:
mViewModel.onSomethingHappened()
Inside ViewModel:
fun onSomethingHappened() {
...
...
...
mLiveData.value = NEW_VALUE
}
If you want to update your LiveData from another thread use:
mLiveData.postValue()

Update value of LiveData everytime one of other LiveData updates its value

I have a LiveData which contains a List like so:
val originalSourceLiveaData = MutableLiveData<List<SomeType>>()
Now I have another LiveData which should indicate the filtering of the originalSourceLiveaData's value.
val filterLiveData = MutableLiveData<String>()
What I want is that everytime either one of those LiveData change value, a resulting list should be updated. I tried doing something like this:
val filteredListLiveData = MediatorLiveData<List<SomeType>().apply {
addSource(originalSourceLiveaData) { this.value = filteringMethod() }
addSource(filterLiveData) { this.value = filteringMethod() }
}
This works just fine but I wonder whether there is a better solution to this.
My issue is that if another LiveData is added I would have to add it as source like so:
val filteredListLiveData = MediatorLiveData<List<SomeType>().apply {
addSource(originalSourceLiveaData) { this.value = filteringMethod() }
addSource(filterLiveData) { this.value = filteringMethod() }
addSource(anotherSourceLiveData) {
this.value = filteringMethod() // this feels like a duplicate
}
}
Any ideas on improving this? Thanks in advance!
You can make it more reactive-style using the extension function feature of Kotlin.
Assume that you have firstLiveaData and secondLiveData with the same type of T. Now you want to filter them first and then listen to all of their changes.
So, you can add the following extension functions:
filter function will filter your livedata based on the given predicate function
addSources function will do the boilerplate of adding multiple livedata and listen to their changes
fun <T> LiveData<T>.filter(predicate : (T) -> Boolean): LiveData<T> {
val mutableLiveData = MediatorLiveData<T>()
mutableLiveData.addSource(this) {
if(predicate(it))
mutableLiveData.value = it
}
return mutableLiveData
}
fun <T> MediatorLiveData<T>.addSources(vararg listOfLiveData: LiveData<T>, callback: (T) -> Unit) {
listOfLiveData.forEach {
addSource(it, callback)
}
}
Also, you can merge multiple LivaData objects with the same type into one with merge function:
fun <T> merge(vararg liveDataList: LiveData<T>): LiveData<T> {
val mergedLiveData = MediatorLiveData<T>()
liveDataList.forEach { liveData ->
liveData.value?.let {
mergedLiveData.value = it
}
mergedLiveData.addSource(liveData) { source ->
mergedLiveData.value = source
}
}
return mergedLiveData
}
Here is an example:
fun doSomething() {
val firstLiveData = MutableLiveData<List<SomeType>>()
val secondLiveData = MutableLiveData<List<SomeType>>()
merge(firstLiveData, secondLiveData).filter { someFilterFunction() }.observe(...)
}
If you have a different type of LiveData (e.g. firstLiveData<Int> and secondLiveData<String>), you can simply add a map extension function.

Categories

Resources