Hi everyone did anyone ever had a problem with Sta...
# flow
v
Hi everyone did anyone ever had a problem with StateFlow when calling update state one after the other ? I am facing a issue like this:
Copy code
val state = MutableStateFlow("a")
val stateList = mutableList()
val job = launch { state.collect(stateLost::add) }
state.update {"b"}
state.update {"c"} 
job.cancel()
//Expected
["a", "b", "c"]
//What actually happens
["a", "c"]
But if i add s small delay i got the expected result.
Copy code
state.update {"b"}
delay(1)
state.update {"c"}
["a", "b", "c"]
e
are you sure you want a
StateFlow
? states are always conflated - if multiple states are set before the collectors run, they only see the latest value
v
Okay now I see, so the state is updated before the new value can be collected. Yes cause I’m using on a ViewModel + Compose, also because i need to be able to do things like:
state.update{ it.copy(newValue) }
k
@Vinícius Santos as long as you’re ok with losing intermediate values, you should be fine. Which is to say - according to my understanding of the
update
function - you don’t need to worry about accidentally getting “c” first and then “b” becomes the latest (in a multithreaded situation more complicated than your simple example). So, given your description of ViewModel + Compose, it sounds to my like you’re good to go and don’t need to worry. But, again, if you want to be notified of each and every value - no matter how fast they come, then you definitely don’t want
StateFlow
.
…and perhaps this is helpful clarification, the values are conflated meaning “b” was in fact set first, and then “c”, it just didn’t publish both. So, you should be fine as your second
update
call will be running (effectively) “bValue.copy(cValue)”
v
Okay, think I get it, thanks for the help guys!!