Kotlin

StateFlow — Observable State

admin by @admin ADMIN
3m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`StateFlow<T>` is a hot Flow holding a single current value. Perfect for UI state in Compose/Android — always has a value, conflates intermediate values, multi-subscriber.
Kotlin
Raw
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class CounterViewModel {
    private val _count = MutableStateFlow(0)
    val count: StateFlow<Int> = _count.asStateFlow()       // read-only view

    fun increment() { _count.value++ }
    fun reset()     { _count.value = 0 }
}

fun main() = runBlocking {
    val vm = CounterViewModel()

    // Collect updates
    val job = launch {
        vm.count.collect { println("count=$it") }
    }

    delay(50);  vm.increment()
    delay(50);  vm.increment()
    delay(50);  vm.reset()
    delay(100); job.cancel()

    // StateFlow ALWAYS has a value — useful for "current state":
    println("final = ${vm.count.value}")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.