Be careful with asLiveData extension

Android Memo 5

Maybe it’s only me so careless. But here is a warning about `asLiveData` extension.

val hotData: LiveData<Int> = Model.sharedFlow.onEach {
Log.d("MY_FLOW", "hot flow on each: $it")
}.asLiveData()

STR
1. Observe hotData from a fragment. Usually we do this from onViewCreated
2. Go to another fragment and stay there for 5 seconds (default timeout)
3. Go back to initial fragment and observe hotData again.
4. See in logs, that onEach clause runs again.

Thing is, that after timeout Flow behind LiveData re-executed. In case of a cold flow nothing happens, because flow is complete and won’t be re-collected.
But for hot flow code in onEach with execute again. If you do some work there, you could face bugs. I learned this hard way, hope you will avoid it.

--

--

Sviatoslav Melnychenko
Sviatoslav Melnychenko

No responses yet