https://kotlinlang.org logo
#flow
Title
# flow
d

dephinera

10/25/2021, 9:25 AM
Instead of LiveData, I'm using StateFlow in my ViewModel to emit values to the UI. I realized that StateFlow doesn't emit equal values. How do you approach that? What if you want to emit multiple times the same value to show some message pop-up/toast/smth?
b

bezrukov

10/25/2021, 9:27 AM
you can use SharedFlow, it doesn't conflate equal values
one more drawback of using StateFlow for your use case is that StateFlow is also drops emission if collector wasn't able to consume it before new one arrives. For example:
Copy code
state.value = Toast("Text A")
state.value = Toast("Text B")
state.value = Toast("Text C")
Collector [most likely, it depends on collector's Dispatcher] will receive only "Text C" It also can be fixed with shared flow by introducing extra buffer
d

dephinera

10/25/2021, 9:32 AM
Thanks!
j

Javier

10/25/2021, 11:35 AM
if the state is not changing, what is the reason to redraw the scren?
d

dephinera

10/25/2021, 11:41 AM
As I mentioned, this might be a popup. For example a toast message that displays "success" every time an operation success
j

Javier

10/25/2021, 11:50 AM
then you have to wonder if you are going to manage them as state or as event
d

dephinera

10/25/2021, 11:51 AM
You're right that it's more like an event. What would be the proper approach in that case? Is MutableSharedFlow still the way to go
j

Javier

10/25/2021, 11:51 AM
and probably you should use channels instead of shared flow if you go for events
d

dephinera

10/25/2021, 11:51 AM
I see
Channels are used to handle events that must be processed exactly once* (see sidenote below for details).
another option is reset de state
but not sure if toast allow to know when they are disappearing
d

dephinera

10/25/2021, 1:43 PM
After reading the article, MutbaleSharedFlow still sounds as the best fit for the scenario
k

Kamil Kalisz

10/26/2021, 6:51 AM
You can always wrap your event in some generic Event class. ( Or expand your base class) that will contain for example creation timestamp. So each event even with the same message will be different in terms of equality
d

dephinera

11/01/2021, 6:43 AM
This sounds more like a "fighting the framework" solution
2 Views