I’m looking to convert some `LiveData` to `StateFl...
# flow
j
I’m looking to convert some
LiveData
to
StateFlow
. What would be the equivalent flow construct for the
CoroutineLiveData
builder function?
Copy code
val state = liveData {
    emit(loadState())
}

suspend fun loadState(): State = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    ...
}
The closest I can determine is:
Copy code
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:
Copy code
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.
f
You can set an initial state and filter on it. Either as a nullable value, or if you don’t nullable a concrete type (e.g. sealed class). You can then filter either from the consumer side or from the producer side.
j
That's somewhat what I've settled on. It seems if the StateFlow interface is needed by the consumer (the view), in order to access the value property directly, then the consumer needs to filter out the nulls when collecting. If the consumer doesn't care that the Flow is a StateFlow (doesn't require the current state value property), then the producer can filter the StateFlow and just provide a vanilla Flow interface.