Fudge
09/18/2021, 8:21 AM.collect {}
call of a MutableStateFlow
not work after the initial value?
Basically, I create a MutableStateFlow
in one place and call emit
(multiple times) there, and at the same time call .collect {}
in another place, and the callback of collect
is not executed, except for the initial value. I can clearly see the state of the Flow
is changing, but collect
is just not working.
I'm also absolutely sure the collect
call is not getting canceled, as I have tried catching CancellationException
.
The context is a Jetpack Compose app, maybe it's some bug there?
SOLVED: the problem was emitting the same list to the StateFlow. Even though the list is changing, its reference has not, and coroutines treat it as the same value, and concludes no new value needs to be emitted. Hence collect
callback is not called after the initial value.Albert Chang
09/18/2021, 8:33 AMmutableStateFlow.value = newValue
instead of emit()
?uli
09/18/2021, 8:59 AMFudge
09/18/2021, 9:16 AMAlbert Chang
09/18/2021, 9:18 AMemit()
is a suspend function and it needs dispatching so there may be some timing issues. That's why I asked you why you are using the suspend function to update the value.Fudge
09/18/2021, 9:44 AM.value =
Values in state flow are conflated using Any.equals comparison in a similar way to distinctUntilChanged operator. It is used to conflate incoming updates to value in MutableStateFlow and to suppress emission of the values to collectors when new value is equal to the previously emitted one.
uli
09/18/2021, 10:15 AMFudge
09/18/2021, 10:16 AMAlbert Chang
09/18/2021, 10:21 AMMutableList
as state is suspicious and error-prone. You should always use immutable List
as state.Fudge
09/18/2021, 10:24 AM