android-livedatakotlin-coroutinesandroid-ktx

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


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 ?


Solution

  • 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.