// Created on savesnippets.com · https://savesnippets.com/3zpi9s4aPPKdLJ import kotlinx.coroutines.* import kotlinx.coroutines.flow.* class CounterViewModel { private val _count = MutableStateFlow(0) val count: StateFlow = _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}") }