Jeff Lockhart
03/16/2021, 5:31 AMLiveData
to StateFlow
. What would be the equivalent flow construct for the CoroutineLiveData
builder function?
val state = liveData {
emit(loadState())
}
suspend fun loadState(): State = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
...
}
The closest I can determine is:
val state = flow {
emit(loadState())
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
Except that stateIn()
requires an initial value, which doesn’t make this quite the same, as I don’t want any value collected until the state is loaded.
Another possibility might be to use the shareIn()
operator to create a SharedFlow
with replay set to 1. This might be a closer equivalent in some ways:
val state = flow {
emit(loadState())
}.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000), replay = 1)
Except SharedFlow
doesn’t provide a value
property to get the current state. Which makes the StateFlow
construct with a nullable type a closer equivalent in this regard.Fredrik Larsen
03/17/2021, 10:29 AMJeff Lockhart
03/17/2021, 2:15 PM