0
0
Kotlinprogramming~5 mins

StateFlow for observable state in Kotlin

Choose your learning style9 modes available
Introduction

StateFlow helps you keep track of changing data in your app. It lets parts of your app watch for updates and react right away.

When you want to show live updates on the screen, like a timer or score.
When multiple parts of your app need to know about the same changing data.
When you want to handle user input and update the UI automatically.
When you want to keep your app's state safe and easy to manage.
When you want to avoid manual event handling and use reactive programming.
Syntax
Kotlin
val stateFlow = MutableStateFlow(initialValue)

// To observe changes:
stateFlow.collect { value ->
    // react to value
}

// To update value:
stateFlow.value = newValue

MutableStateFlow lets you change the value.

Use collect inside a coroutine to watch for updates.

Examples
Create a StateFlow holding a number and change it.
Kotlin
val count = MutableStateFlow(0)

// Update count
count.value = 5
Collect values from StateFlow inside a coroutine to react to changes.
Kotlin
lifecycleScope.launch {
    count.collect { value ->
        println("Count is $value")
    }
}
Change and read the current value directly.
Kotlin
val stateFlow = MutableStateFlow("Hello")

stateFlow.value = "Hi"

println(stateFlow.value)
Sample Program

This program creates a StateFlow holding a number. It watches for changes and prints them. Then it updates the number three times with a delay.

Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val stateFlow = MutableStateFlow(0)

    // Launch a coroutine to observe changes
    val job = launch {
        stateFlow.collect { value ->
            println("Observed value: $value")
        }
    }

    // Update the stateFlow value
    repeat(3) {
        delay(500)
        stateFlow.value = it + 1
    }

    job.cancel() // stop collecting
}
OutputSuccess
Important Notes

StateFlow always has a current value you can read anytime.

Collecting from StateFlow must happen inside a coroutine.

Use MutableStateFlow to change the value, but expose it as StateFlow to others for safety.

Summary

StateFlow holds data that changes over time and lets others watch those changes.

Use MutableStateFlow to update data and collect to react to updates.

It helps keep your app's state clear and reactive.