Managing state in Android with Kotlin StateFlow: A beginner's guide

Photo by Matt Hardy on Unsplash

Managing state in Android with Kotlin StateFlow: A beginner's guide

Managing states in Android can be complex, especially when dealing with asynchronous and streaming data.

In this article, we'll look at how we can remove this complexity using kotlin flows.

Flows, What are they?

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

StateFlows?

Kotlin's Stateflow is a new feature that provides a way to handle states in a more structured and composable way. It's a type of flow that holds a value and allows you to emit new values. It also provides a way to access the current value of the flow.

One of the main benefits of using Stateflow is that it allows you to manage state changes in your app more reliably and efficiently. It allows you to easily update the value of the flow and notify the observers about the change.

TLDR;

Flows are a way of emitting values, sequentially unlike suspending functions, which return one value at a time. Stateflow allows you to manage changes in your app more efficiently and reliably, making it easy to achieve reactiveness in your app.

How do I use Stateflow in my app?

To use Stateflow in your app, you need to add the kotlinx-coroutines-core and kotlinx-coroutines-android libraries to your app's dependencies.

You need to add the following dependencies to your app's build.gradle file:

def coroutines_version = '1.6.1'
// Coroutines core library
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
// Coroutines android library
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
//viewModel by delegation
implementation 'androidx.activity:activity-ktx:1.6.1'
//Android KTX extensions
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'

Your final app's level build.gradle dependencies should look like this:

Once you have added these dependencies to your project and synced your gradle, you can start using Stateflow in your code.

It's worth mentioning that the version numbers may be different depending on the version you are using, please check the kotlin website for the latest version.

To demonstrate Stateflow, we're going to be building a simple counter app, that increments the value of a text on button click.

For this, we'll be making use of a ViewModel to expose our states to the activity, responsible for displaying our data.

In the above example, MyViewmodel class extends ViewModel, then we have a property called counter with an initial value of mutableStaflow 0, We have a function that increments the value of the counter property by 1.

We're going to launch our ViewModel class from the mainActivity.kt file.

We used View binding to initialize our UI, then called the incrementCounter() method of our ViewModel when the button is clicked on.

Finally, We launch our viewModel in a lifecycleScope method because we can only launch ViewModel in a coroutine which is provided by lifecycleScope

The repeatOnLifecycle function is being used to ensure that the coroutine only emits data when the app is in the "STARTED" state, meaning it is visible to the user and not in the background.

Activity Main XML

We have used view binding for this example so, you might need to enable it from your app level build.gradle file:

android {
   //....
    buildFeatures{
        viewBinding = true
    }
}

That's it guys! I hope that by now you understand what flows are and how we can use them in our projects. I have a little challenge for you, YES, YOU!

From the example, create a function in the ViewModel that decrements the counter and call this function when the button is long-pressed

Please feel free to reach out to me on any of the channels below, should you get stuck or have any android related questions (or programming in general), I'd be glad to help

Additional flow resources