liveBook · Manning

MutableStateFlow

As explained in Kotlin in Action, 2E

MutableStateFlow is a kotlinx.coroutines type that represents a state flow whose current value can be updated.

MutableStateFlow represents changeable state in Kotlin coroutines. Create it with an initial value, keep it private, and expose a read-only StateFlow to subscribers. section 16.3.2

Listing 16.13 A basic implementation of a view counter that uses a state flow
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*
 
class ViewCounter {
    private val _counter = MutableStateFlow(0)    #1
    val counter = _counter.asStateFlow()
 
    fun increment() {
        _counter.update { it + 1 }
    }
}
 
fun main() {
    val vc = ViewCounter()
    vc.increment()
    println(vc.counter.value)
    // 1
}

A view counter demonstrates the standard pattern: initialize MutableStateFlow, expose asStateFlow(), update with update, and read the current value without suspending. section 16.3.2

Use MutableStateFlow for state that must remain safe and observable:

  • Read the current state through value. section 16.3.2
  • Update state with update rather than relying on a nonatomic ++ operation. section 16.3.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains creation, exposure, reads, atomic updates, conflation, and cold-flow conversion, but defers broader state-flow topics.
Examples
Uses a view counter, 10,000 concurrent increments, a direction selector, equality conflation, and temperature conversion.
What it assumes
Assumes Kotlin coroutines and flow terminology while demonstrating the MutableStateFlow pattern from initialization onward.
What you can do after
Apply it via kotlinx.coroutines to expose state safely, update it concurrently, collect changes, and convert cold flows into state.
How it connects
Connects MutableStateFlow with StateFlow, SharedFlow, cold flows, hot flows, coroutines, update, and stateIn.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.