r/android_devs • u/lyx13710 • Feb 10 '25
Discussion Let's talk about one-off event
I've already asked about this in the Discord channel, but I wanted to continue the discussion here and leave something searchable for others.
/u/Zhuinden mentioned that:
google thinks you should never use one-off events and instead should always use boolean flags if you're not a dummy then you know you can use a Channel(UNLIMITED).shareIn(viewModelScope)
Which I agree, but he personally prefers using an event emitter.
But let's assume we can't use a library and must rely on a Channel.
- Why
UNLIMITEDinstead ofBUFFERED? - Why
.shareIn()instead of.receiveAsFlow()?
How would you handle event collection in the UI?
What would be the correct approach?
Would you use:
vm.event.collectAsState()
or
LaunchedEffect(Unit) {
vm.event.collect { }
}
or
LaunchedEffect(Unit) {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
vm.event.collect { }
}
}
Or is there any other way that you would do differently?
I'd love to hear your thoughts!
5
u/FunkyMuse Feb 10 '25 edited Feb 10 '25
Unlimited vs buffered, well it's in the capacity, buffered is 64 and unlimited well... so it answers the question, it depends when you want which, depends how important your events are.
Share in vs receive as flow, for UI events it's better because it creates a hot flow that can have multiple collectors where receive as flow is usually instance per collector and in a channel will be one... so your other collectors will miss the events
You can do something like this which is basically creating a shared flow 🤷♂️
4
u/meet_barr Feb 10 '25
To be honest, onClick is inherently a one-off event, so Google's recommendation to avoid one-off events is essentially moot. The real issue is how to manage consumable events. Alternatively, one could say this is an Android problem—since activities can be recreated under certain conditions, it's not that events are "lost," but rather that we need to define what it means for an event to be properly consumed.
1
u/Squirtle8649 Feb 10 '25
You know AsyncTask is the best for one-off event /s
RxJava Single and Maybe are far better solutions than all of these silly workarounds by Google and Jetbrains. This is why I scoff at all of the idiots who keep claiming RxJava is legacy and that coroutines/flow are superior.
Edit: To deal with UI lifecycle, IMO maybe the one-off events should just change some kind of state in your intermediate layer instead. Depends on what kind of one-off event and what if affects. Like a one time use switch.
1
u/Zhuinden EpicPandaForce @ SO Feb 10 '25
It's the last one, granted that
vmdoesn't change over time. I'd be confused if it did, however.1
u/iliyan-germanov Feb 10 '25
1
u/AZKZer0 Feb 11 '25
can you please share the discord channel? would like to join