Better observable DS in Android
StateFlow vs LiveData

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.

要查看或添加评论,请登录

Siddhant Mishra的更多文章

  • Lambda functions

    Lambda functions

    Today I will be writing about two different yet intriguing way to write the lambda functions in Kotlin. Conventionally…

    1 条评论
  • Exceptions in Coroutines

    Exceptions in Coroutines

    Hi everyone, today I will be writing about exceptions in Coroutine and how to handle them gracefully. First let us see…

  • Trie data structure

    Trie data structure

    Today I will write about a magical data structure namely Trie. When we talk of storing and retriving some information…

  • Vertical Order traversal in binary tree

    Vertical Order traversal in binary tree

    We generally talk about Inorder, PreOrder, PostOrder and LevelOrder traversals in binary tree, but we generally do not…

  • LCA in Binary Tree

    LCA in Binary Tree

    Today I will be writing about the LCA(Least Common Ancestor) for a binary tree. LCA refers to the node in the binary…

  • Delegates in Kotlin

    Delegates in Kotlin

    Today I will be writing about my understanding regarding the delegates in Kotlin. The english meaning of Delegation…

  • TypeAlias in Kotlin

    TypeAlias in Kotlin

    Today I will be writing about TypeAlias in Kotlin and how do I understand and use it in my day to day coding. Typealias…

  • Reified in Kotlin

    Reified in Kotlin

    Today I will be writing about the type erasure in Java and Kotlin and its solution. The concept of type erasure stems…

    1 条评论
  • Jetpack Compose - Interesting features to dive deeper into.

    Jetpack Compose - Interesting features to dive deeper into.

    Recently I got to migrate my sample project from the conventional XML to Jetpack Compose, and I would like to list down…

    3 条评论
  • Hot flow vs Cold flow in Kotlin

    Hot flow vs Cold flow in Kotlin

    Today I will try to discuss the salient dissmilarities between Hot and Cold flow in Kotlin. Going from the basics, flow…

社区洞察