So I'm trynna replace my LiveData with a StateFlow...
# coroutines
s
So I'm trynna replace my LiveData with a StateFlow. I want to trigger an update whenever it's first accessed. I was using
liveData
builder before like this:
Copy code
val users = liveData {
    emit(getUsers(count=20))
}
With StateFlow, I'm doing it with `lazy`:
Copy code
val users by lazy {
    MutableStateFlow<List<User>>(listOf()).also { usersFlow ->
        viewModelScope.launch {
            usersFlow.value = getUsers(count = 20)
        }
    }
}
Just wanna know if it's fine to do it this way?
e
Not sure if entirely equivalent, but could you simply
MutableStateFlow(...).onStart { emit(getUsers(count = 20)) }
?
s
I tried but it doesn't work for me. I think it would work if I added a
collect
after the
onStart
but that's not how I'm doing it. Also
onStart
converts it to
Flow
so I can't add that while initializing
e
Your UI should be collecting the flow. When that starts, the underlying mutable state flow emits the value before anything else
s
I'm using jetpack compose. I'm collecting the flow using
StateFlow.collectAsState
but the
onStart
never runs. Is this a bug?
e
Well, there's the initial value of a mutable state flow, but I'm sure you had noticed that before
s
Yep the initial value is collected which is an empty list but
onStart
never gets called
e
onStart is only called when a collector starts collecting
s
Yes I'm collecting using collectAsState from jetpack compose
e
For simplicity I guess that your suggested code should be fine, unless you don't want to emit and empty list initially.
s
Alright. I'd probably wrap it in a network state later