I was following this article (<https://medium.com...
# compose
p
I was following this article (https://medium.com/androiddevelopers/viewmodel-one-off-event-antipatterns-16a1da869b95) for implementing a solution for events in compose. But as far as I can tell, if the time between the state changes is too quick, the compose might drop the first change updates and only use the last state update for the next recomposition. If this is the case then using this supposed state based event silver bullet might be dangerous in certain use cases because the state changes (ie events) might get dropped. Is there something I'm missing here? Is this intended or these drawback are mitigated somehow?
m
I’m just seeing this article. The first “anti-pattern” he mentioned is what I usually use. The approach he suggested has led to bugs for me in the past, precisely the scenario you described — when two consecutive state updates are made, it ignores one
👍 1
Perhaps take a look at the comments, there are some helpful counter arguments there. I’ve been bitten hard enough to know not to use StateFlow to fire events.
👍 1
p
For event or effects as they are also called, use MutableSharedFlow and ensure you dispatch their emitt with Dispatchers.Main.immediate. You can create a helper extension function for that. But the article is right in the sense that, a collector might unsubscribe just within that millisecond timeframe where the event travels from the emitter to the collector. The only way is ensuring the emission and consumption is performed in the current loop. StateFlow is conflated, you can still model a proper solution around them but be careful with conflation.
If you need to keep the latest you can set reply = 1 in the SharedFlow. Then to not double consume, keep a reference of the last event received in the View side. If the event that comes from the flow is the same as the last event. That means you consume it already, and then you ignore it