Michael Ferguson
1 min readMar 31, 2023

--

Channels fail as an emitter of events because of this issue: https://github.com/Kotlin/kotlinx.coroutines/issues/2886 (I'm disappointed too.)

Ignoring that bug, I'm speculating why google says they fail the UDF pattern but I think it's because they don't complete the loop. An event is emitted, observed but overall state is never updated to indicate the event is consumed and state is changed. (They are being UDF purists in this case.)

Personally, I don't like SingleLiveEvent style event wrappers when used in combination with a conflating holder like live data. This is because it's possible to emit two back to back events. If there's no observer the first event is destroyed. The actual event wrapper is fine assuming the guard that marks it consumed is thread safe. It's the thing that holds those wrapped events that is a problem.

Once you get away from conflating event holders like LiveData or StateFlow then the need to use a wrapper diminishes dramatically because an observed event is removed from whatever is holding it.

FWIW google's suggestion is basically to use event wrappers with a conflating state holder. So rather than a SingleLiveEvent style event wrapper they are just removing an event from a list in a stateflow state holder based on something unique, like a UUID. They even update it atomically using stateflow's update function.

--

--

Michael Ferguson
Michael Ferguson

Written by Michael Ferguson

Android software developer. Views and opinions expressed are my own and not that of my employer.

No responses yet