I need to get a liveData from the return value of a suspend function. For this -
val apiLiveData = MutableLiveData<MenuItem?>()
fun getLiveData(): LiveData<MenuItem?> {
viewModelScope.launch {
apiLiveData.postValue(Repository.getMenuItem())
}
return apiLiveData
}
val apiLiveData: LiveData<MenuItem?> = liveData {
emit(Repository.getMenuItem())
}
Which of the above method should I use ?
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.