StateFlow Examples in android | ViewModels in Kotlin

This tutorial will help you learn about StateFlow usage in Android using simple step by step isolated examples.

What is Stateflow? 

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

  • In Android, StateFlow is a great fit for classes that need to maintain an observable mutable state.
  • For example a StateFlow can be exposed from the YourViewModel so that the View can listen for UI state updates and inherently make the screen state survive configuration changes.

Here is code usage example:

In the fragment onCreate:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        val homeViewModel: HomeViewModel by viewModels()
        //.......................................................
        // trigger state flow
        binding.stateFlowButton.setOnClickListener {
            homeViewModel.triggerStateFlow()
        }


        // launchWhenStarted {…} gets suspended when onStop() is called
        lifecycleScope.launchWhenStarted {

           // Triggers the flow and starts listening for values

            // Collect will collect every value ,
            // and CollectLatest will stop current work to collect latest value,
            homeViewModel.stateFlow.collectLatest {
                binding.stateFlowButton.text = it
            }
            /*So , if every update is important like state, view, preferences updates, etc ,
            collect should be used .
            And if some updates can be overridden with no loss ,
            like database updates , collectLatest should be used.*/

        }

    }

View model:

package com.boltuix.viewbinding

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class HomeViewModel : ViewModel() {

    private val _textStateFlow = MutableStateFlow("Hello World")
    val stateFlow =_textStateFlow.asStateFlow()

    fun triggerStateFlow(){
        _textStateFlow.value="State flow"
    }

}

/*
The documentation of asStateFlow() is pretty clear about this:
Represents this mutable state flow as a read-only state flow.
To make it easier to understand, if you use HomeViewModel in a component,
this outsider will be able to read the values but not write them..
* */

..

Note

  • A regular Flow is cold but StateFlow is hot. 
  • It means that the regular Flow does not have the concept of the last value and it only becomes active when it gets collected, whereas StateFlow has the concept of the last value and it becomes active as soon as we create it.
What is ViewModel
  • ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way.
  • It is the main component in the MVVM architecture.
  • ViewModel can be created with activity context or fragment context.
  • When a ViewModel object is created, it is stored inside Activity OR FragmentManager.
Advantages of using View Model
  • Handle configuration changes: ViewModel objects are automatically retained whenever activity is recreated due to configuration changes.
  • Lifecycle Awareness: ViewModel objects are also lifecycle-aware. They are automatically cleared when the Lifecycle they are observing gets permanently destroyed.
  • Data Sharing: Data can be easily shared between fragments in an activity using ViewModels.
  • Kotlin-Coroutines support: ViewModel includes support for Kotlin-Coroutines. So, they can be easily integrated for any asynchronous processing.

Live data, Flow, Shared flow & State flow 
You'll learn the differences between the typical observable classes we have in Android


Comments