Better observable DS in Android
Today I would like to have a thorough discussion on the purpose of using observable data structures in our Android application and which one is better to use - StateFlow or LiveData.
Firstly before going into the main discussion, let us understand the need of observables in any scenario in software development lifecycle.
The concept stems to one of the most popular Design Patterns in low level design namely Observer Design Pattern which has a set of events and there is a set of observers. Also we have the facility to register and unregister specific observers on specific events as per our requirements. Then the registered observers are invoked when the specific events take place and going ahead we can carry out whatever we want to in that case.
Now coming to the Android context, there is an imperative role these observable data structures play owing to the fact that they help us perform Reactive Programming efficiently. Now by reactive programming I simply mean, the promptness with which our application responds to the user inputs after handling the meddling asynchronous tasks gracefully.
Most popularly we use StateFlow and LiveData as the observable data structures in android.
Moving into the comparison -
Now using Livedata helps us make our observation lifeCycle aware while in StateFlow we have to add the extra condition to make it lifecycle aware something like this -
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
// Your code here
}
}
And liveData does it internally using this -
@Override boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
By making it lifeCycle aware I mean - we need not try to observe the data structure and try to manipulate the UI/view when the view is not in the foreground(It leads to a crash otherwise).
Another set of comparison goes something like this -
LiveData class exists inside the package androidx.lifecycle which makes it tightly linked/coupled to the android framework, which theoretically does not go well with the solid principles we have read so far and in contrast to that StateFlow is aply decoupled from the Android framework.
Moving on to the next comparison -
As per the observation, StateFlow is a better choice than the LiveData in case there are a lot of observers for an event and also it goes really well with Coroutines and Flows which are again the powerful mechanisms to handle the async tasks.
Overall StateFlow code looks something like this -
lifecycleScope.launchWhenStarted {
viewModel.sampleUiState.collect {
when (it) {
// Handle the success, error and the loading cases.
}
}
}
Long story short - It depends on your specific requirements if you go with stateFlow and LiveData. Both are graceful observable data structures. You can try implementing both and check the efficacies.
Thanks for reading.