Live Data

Live data is part of Android Architecture Components which are basically a collection of libraries that help you design robust, testable, and maintainable apps.

It is an Observable data class — Meaning it can be observed by other components — most profoundly UI controllers (Activities/Fragments). So, instead of having a reference of the activity/fragment in your ViewModel (which you shouldn’t have due to leaks), you now have a reference to the ViewModel in the activity/fragment

It is Lifecycle aware— Meaning it sends updates to our UI (Activities/Fragments) only when our view is in the active state. (No memory leaks)

Creating an instance of LiveData,

Set the data in LiveData,

The MutableLiveData publicly exposes two methods i.e. setValue and postValue to set the data in LiveData.

  1. If you are working on the main thread, then both setValue and postValue will work in the same manner i.e. they will update the value and notify the observers.
  2. If working in some background thread, then you can’t use setValue. You have to use postValue.

Observe the data changes,

If there is a change in data then that data will be reflected to all the observers associated with it but it only notifies the changes to the observers that are live or in the active state and not to that observer that are in the inactive state.

Using LiveData provides the following advantages:

  • No memory leaks
  • Ensures your UI matches your data state
  • No crashes due to stopped activities
  • Always up to date data
  • Proper configuration changes
  • Sharing resources

Drawbacks Of LiveData

  • Lack of control over the execution context
  • Threading issue especially when used in Repositories
  • Not built on top of Coroutines and Kotlin
  • Lack of seamless data integration across between database and UI especially using Room.
  • Lots of Boiler Plate Codes especially while using Transformations

Flows

In coroutines, a flow is a type that can emit multiple values sequentially, as opposed to suspend functions that return only a single value. For example, you can use a flow to receive live updates from a database.

Flow can handle streams of values, and transform data in complex multi-threaded ways.

A Flow object is what Observables / Flowables are in the Rx world, they represent a stream of specific values.

can be translated to,

The Flow starts emitting data when collect() is called on the stream, so that

Flows are usually cold! This means, that a flow only emits data when it is collected (or consumed).

A flow can now also be a hot flow, before collecting a normal flow, you can now call,

This will keep the flow alive as long as the attached scope is not canceled. You can basically re- use that flow and keep emitting items. In other words, shareIn transforms that flow into a SharedFlow, yet the type reflected by the API can be a simple Flow.

StateFlow and SharedFlow

StateFlow and SharedFlow are Flow APIs that enable flows to optimally emit state updates and emit values to multiple consumers.

StateFlow

StateFlow is a state-holder observable flow that emits the current and new state updates to its collectors.

The current state value can also be read through its value property.

To update state and send it to the flow, assign a new value to the value property of the MutableStateFlow class. StateFlow only returns a value that has been updated. State Flow is similar in concept with Observer of RxJava. When collecting value from StateFlow, we always get the latest value as it always has a value that makes it read-safe because at any point in time the StateFlow will have a value. Infact, stateFlow requires an initial value.

Creating an instance of StateFlow,

Emit the data in StateFlow,

Collecting the data changes,

SharedFlow

The shareIn function returns a SharedFlow, a hot flow that emits values to all consumers that collect from it. A SharedFlow is a highly-configurable generalization of StateFlow.

Creating an instance of SharedFlow,

Emit the data in SharedFlow,

Collecting the data changes,

The main difference between a SharedFlow and a StateFlow is that a StateFlow takes a default value through the constructor and emits it immediately when someone starts collecting, while a SharedFlow takes no value and emits nothing by default.

StateFlow and LiveData have similarities. Both are observable data holder classes, and both follow a similar pattern when used in your app architecture.

The StateFlow and LiveData do behave differently:

StateFlow requires an initial state to be passed into the constructor, while LiveData does not.

LiveData.observe() automatically unregisters the consumer when the view goes to the STOPPED state, whereas collecting from a StateFlow or any other flow does not stop collecting automatically. To achieve the same behavior,you need to collect the flow from a Lifecycle.repeatOnLifecycle block.

Finally,

LiveData

LiveData is a lifecycle aware observable data holder (means it knows the lifecycle of the activity or a fragment) use it when you play with UI elements(views).

Flow

Flow (cold stream) – In general think of it like a stream of data flowing in a pipe with both ends having a producer and consumer running on a coroutine.

StateFlow

StateFlow(hot stream) does similar things like LiveData but it is made using flow by kotlin guys and only difference compare to LiveData is it’s not lifecycle aware but this is also been solved using repeatOnLifecycle api’s, so whatever LiveData can do StateFlow can do much better with power of flow’s api. StateFlow won’t emit same value.

SharedFlow

SharedFlow(hot stream) – name itself says it is shared, this flow can be shared by multiple consumers, I mean if multiple collect calls happening on the sharedflow there will be a single flow which will get shared across all the consumers, unlike normal flow.

Channel

SharedFlow as a hot flow will emit data even if no one listening. Channel will hold data till someone consumes it. So if your view is not ready to receive an event and sharedFlow emits it, the event will be lost. So channels are better to send one-time events. Obviously, you can set reply count for shared flow, but then your event will be repeated.

About Logidots

Logidots is an app development agency that works with startups and enterprise to ideate and develop new products. We’ve built products that raised over millions in funding and got into startup accelerators like YC.

Hire an expert Android developer

Love Reading Success Stories?
Then Why Not Write One For Yourself?