0
0
Android Kotlinmobile~5 mins

StateFlow for reactive state in Android Kotlin

Choose your learning style9 modes available
Introduction

StateFlow helps your app react to changes in data automatically. It keeps your app's state updated and UI in sync without extra work.

When you want your app to update the screen automatically when data changes.
When you need to share data between different parts of your app and keep it consistent.
When you want to handle user input and show results immediately.
When you want to avoid manual updates and callbacks for state changes.
Syntax
Android Kotlin
private val _state = MutableStateFlow(initialValue)
val state: StateFlow<Type> = _state

// To update state:
_state.value = newValue

Use MutableStateFlow to change the state inside your class.

Expose StateFlow to other classes to observe changes without allowing them to modify the state.

Examples
This example creates a count state starting at 0 and updates it to 5.
Android Kotlin
private val _count = MutableStateFlow(0)
val count: StateFlow<Int> = _count

// Update count
_count.value = 5
This example holds a text state and updates it to "Hello".
Android Kotlin
private val _text = MutableStateFlow("")
val text: StateFlow<String> = _text

// Update text
_text.value = "Hello"
Sample App

This program creates a simple counter using StateFlow. It prints the count every time it changes. When increment() is called, the count updates and the new value prints automatically.

Android Kotlin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch

class Counter {
  private val _count = MutableStateFlow(0)
  val count: StateFlow<Int> = _count

  fun increment() {
    _count.value += 1
  }
}

fun main() = runBlocking {
  val counter = Counter()

  val job = launch {
    counter.count.collect { value ->
      println("Count is: $value")
    }
  }

  counter.increment() // Count becomes 1
  counter.increment() // Count becomes 2

  job.cancel()
}
OutputSuccess
Important Notes

StateFlow always has a current value, so you can get it anytime with .value.

Use collect to listen for changes and update UI or other parts of your app.

Remember to cancel collectors when they are no longer needed to avoid memory leaks.

Summary

StateFlow holds and emits state updates reactively.

Use MutableStateFlow to change state, and expose StateFlow to observe it.

Collect StateFlow to react to changes and update your UI automatically.