What is the proper Kotlin Flow alternative to Sing...
# android
z
What is the proper Kotlin Flow alternative to SingleLiveEvent?
e
SharedFlow or Channel
z
how does one do this with sharedflow? I seemed to be getting repeat events
e
Perhaps you used StateFlow instead? Can’t really say without seeing your code, should be pretty straightforward. Define a mutable shared flow and emit events to it
j
We use the solution described in this article and it has been working really well for us 🙂 https://proandroiddev.com/android-singleliveevent-redux-with-kotlin-flow-b755c70bb055
👏 2
g
You cannot do this with Flow, you need Channel (though, you can wrap it to flow after that) IMO SingleLiveEvent is anti-pattern, not sure why it even mentioned in official docs as viable solution
☝️ 1
z
so what is the proper way of sending one shot events from the VM? things like navigation, toast/snackbar messages etc?
g
Consumable event with StateFlow
😟 1
z
so something where you can poll the value and when you do it's set as consumed, but can be still be checked for the actual value?
why is that better than the channel/singleliveevent approach?
g
It’s not so different comparing too SingleLiveEvent (so you always have 1 consumer of event), but unlike SingleLiveEvent it at least allows to catch bugs, when you have multiple consumers, so you know that new event is received, but it may be consumed already (which is useful if you just want to know about update, not consume it). Also implementation is waaay easier than SingleLiveData-like solution, it works with any BehaviourSubject-like observable without any changes, you just need super simple wrapper for consumable event yes, I know, everyone says that “event is not state”, and I agree, but I argue that SingleLiveEvent doesn’t solve this, it still state, just hidden, so until we have configuration change case, we should solve it somehow
Perhaps you used StateFlow instead
it will not work as SingleLiveEvent, there is no way to deliver event ony to fist subscriber
so, in short why I think consumable event is better: 1. Very easy to implement, no need to have custom Flow/Observable 2. It explicitly supports multiple observers, so observer can detect that event is consumed and react on it (crash/log/ingore), not like SingleLiveData, which in theory supports multiple observers, but works only for one of them and silently ignores others
z
I haven't had cases where SingleLiveData would require more than one observer, having more observers seems wrong to me
we've been using it for years, and this didn't prove to be an issue so far, but I may be missing something
g
having more observers seems wrong to me
Also true! But if you have a bug, and you got a leak, new observer will receive no events
this didn’t prove to be an issue so far
Until it becomes issue Again, it’s just one of arguments, because implementation is hacky everyone uses this snippet from Android blog and has issue to apply with Flow/Observable
221 Views