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}")
}
Create a free account and build your private vault. Share publicly whenever you want.