Be careful with asLiveData extension

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.

--

--

--

Android Developer @ Appsfactory

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Build a Rock, Paper, Scissors Game With SwiftUI and Combine

Sharing Object Data Between an iOS App and Its Widget

SwiftUI Tutorial: Working with Gesture Composition

simple way for Localization in SwiftUI

SwiftUI Tutorial: Working with TextEditor

SwiftUI — Data transfer between Structs

Scott’s Cheap Flights’​ first mobile application and why we’re building in React Native

How to Build a Live Video Streaming iOS App with Agora

banner image, showing a live streaming app

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sviatoslav Melnychenko

Sviatoslav Melnychenko

Android Developer @ Appsfactory

More from Medium

Dreams on the Screen

Something Suspicious of Malloc()

Depression-I’m sure not only presents differently in everyone but changes over time.

December News — Technology Kiosks