Upgrade to Pro — share decks privately, control downloads, hide ads and more …

LiveData vs. Flow

LiveData vs. Flow

Tamás Fábián

May 23, 2023
Tweet

More Decks by Tamás Fábián

Other Decks in Programming

Transcript

  1. LiveData LiveData is an observable data holder class. Lifecycle-aware, which

    ensures it only updates app component observers that are in an active lifecycle state. “LiveData was never an RX replacement, we've been very clear about this from day 1” - Yigit Boyar
  2. Drawbacks Operates mostly on the main thread. Nullable val liveData

    = MutableLiveData(0) liveData.value++ Part of the Android framework
  3. Flow Kotlin Coroutine's Flow is a stream of data that

    can be asynchronously processed, similar to RxJava's Observable. It is a part of the Kotlin coroutines library and can be used to handle asynchronous operations in an easy and efficient way.
  4. SharedFlow A hotFlow that shares emitted values among all its

    collectors in a broadcast fashion, so that all collectors get all emitted values. A shared flow is called hot because its active instance exists independently of the presence of collectors. This is opposed to a regular Flow, such as defined by the flow { ... } function, which is cold and is started separately for each collector. StateFlow A SharedFlow that represents a read-only state with a single updatable data value that emits updates to the value to its collectors. A state flow is a hot flow because its active instance exists independently of the presence of collectors. Its current value can be retrieved via the value property.
  5. StateFlow In Android, StateFlow is a great fit for classes

    that need to maintain an observable mutable state. • Asynchronous • Transformations • Default value • Null friendly • Backpressure handling
  6. Limitations No official way of surviving process death Not lifecycle

    aware by default StateFlow will re-emit again upon new subscription StateFlow doesn’t re-emit value that is the same
  7. Resources • https://developer.android.com/topic/libraries/architecture/livedata • https://medium.com/mobile-app-development-publication/comparing-android-livedata-and-stateflow-b 2c430863b3a • https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/ • https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flo

    w/ • https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow / • https://developer.android.com/kotlin/flow/stateflow-and-sharedflow • https://medium.com/androiddevelopers/migrating-from-livedata-to-kotlins-flow-379292f419fb