When to use emit() instead of postValue when using livedata with coroutines

1.7k Views Asked by At

I need to get a liveData from the return value of a suspend function. For this -

  1. I can launch a coroutine (using for eg viewmodelScope) and use postValue to update a MutableLiveData instance.
val apiLiveData = MutableLiveData<MenuItem?>()
fun getLiveData(): LiveData<MenuItem?> {
        viewModelScope.launch {
             apiLiveData.postValue(Repository.getMenuItem())
        }
        return apiLiveData
}
  1. I can use livedata {} and emit the returned value of my suspending function.
val apiLiveData: LiveData<MenuItem?> = liveData {
        emit(Repository.getMenuItem())
    }

Which of the above method should I use ?

2

There are 2 best solutions below

0
On BEST ANSWER

If all you're doing is just emitting that one value, I don't see that there is any significant difference between the two, other than one fact. The second example creates a LiveData that stays active for a while during a configuration change. That might not have any significant benefit.

Just go with whatever you are more comfortable with. Seems like the second example is more straightforward with fewer lines of code.

0
On

If you are going to make a liveData with a emit() only, then you better go off with option 1 as it will do the same with less boilerplate.