Michael Ferguson
1 min readSep 24, 2021

--

First, a key thing to point out is the launchWhenStarted helpers do not cancel on stop, they cancel in on destroy. They pause and internally buffer emissions. (This can actually lead to state loss but that's another discussion for another time.)

So regardless of when you launch it, they all cancel when the lifecycle is destroyed, not the opposite side of the life cycle. That in and of itself will give you strange behaviour.

I would argue this specific example is better suited to use a SharedFlow with a SharingStarted of WhileSubscribed.

CallbackFlow, by definition, was designed as a bridge to a non-flow callback environment so it makes perfect sense that it buffers emissions.

If you're trying to avoid the buffered/extra emissions while there are no observers it doesn't really matter how the collector is launched, be it from launchWithXXX or repeatOnLifecycle or even just manual control over the launch job.

Using shared flow allows you to unsubscribe from the upstream when the are no subscribers.

Just do airQualityRepository.observeAirQuality().shareIn(started = SharingStarted.WhileSubscribed)

and you're done. Emissions will stop when the collectors unsubscribe. It doesn't matter what lifecycle management type you use to cause them to unsubscribe.

--

--

Michael Ferguson
Michael Ferguson

Written by Michael Ferguson

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

Responses (1)