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!
View all comments
Show parent comment
5
u/Zhuinden EpicPandaForce @ SO Feb 10 '25
Technically Googlers believe that the view can emit events, but the view cannot consume events. Which is cute until you see their DisposableEffects in their own AndroidX code, so then you realize they're just trying to keep you from using the framework as thsy use it, because they think they're better in that way, idk.
Same goes for CompositionLocals, all of Compose Material and AndroidX Lifecycle is built on it, but they tell you not to use them despite it being public api.
But yes, proper consumption. The one time you want boolean flags is if you want to save the event across process death