https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Se7eN

10/07/2020, 9:50 AM
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

Erik

10/07/2020, 10:51 AM
Not sure if entirely equivalent, but could you simply
MutableStateFlow(...).onStart { emit(getUsers(count = 20)) }
?
s

Se7eN

10/07/2020, 10:54 AM
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

Erik

10/07/2020, 10:57 AM
Your UI should be collecting the flow. When that starts, the underlying mutable state flow emits the value before anything else
s

Se7eN

10/07/2020, 11:02 AM
I'm using jetpack compose. I'm collecting the flow using
StateFlow.collectAsState
but the
onStart
never runs. Is this a bug?
e

Erik

10/07/2020, 11:37 AM
Well, there's the initial value of a mutable state flow, but I'm sure you had noticed that before
s

Se7eN

10/07/2020, 11:40 AM
Yep the initial value is collected which is an empty list but
onStart
never gets called
e

Erik

10/07/2020, 11:41 AM
onStart is only called when a collector starts collecting
s

Se7eN

10/07/2020, 11:43 AM
Yes I'm collecting using collectAsState from jetpack compose
e

Erik

10/07/2020, 1:16 PM
For simplicity I guess that your suggested code should be fine, unless you don't want to emit and empty list initially.
s

Se7eN

10/07/2020, 1:17 PM
Alright. I'd probably wrap it in a network state later