Consider this Kotlin code using StateFlow. What will be printed?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val stateFlow = MutableStateFlow(0) launch { stateFlow.collect { value -> println("Collected: $value") } } delay(100) stateFlow.value = 1 delay(100) stateFlow.value = 2 delay(100) cancel() }
Remember that StateFlow always emits the current value immediately to new collectors.
The MutableStateFlow starts with 0. When collect starts, it immediately emits 0. Then, when the value changes to 1 and 2, those values are emitted as well.
Given a StateFlow instance, what is true about multiple collectors?
Think about how StateFlow behaves like a hot stream that always holds the latest value.
StateFlow is a hot stream that holds the latest value. Every collector immediately receives the current value and then all future updates independently.
Look at this Kotlin code snippet. Why does the collector never print any updates?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val stateFlow = MutableStateFlow(0) stateFlow.collect { value -> println("Value: $value") } stateFlow.value = 1 delay(100) }
Consider how collect works in a coroutine and what happens after it.
The collect call is a suspending function that blocks until the flow completes. Since stateFlow never completes, the code after collect (the value assignment) never runs, so no updates happen.
Choose the correct Kotlin code snippet that creates a MutableStateFlow with initial value 5 and then updates it to 10.
Remember how to create and update a MutableStateFlow.
MutableStateFlow is created with an initial value. You update its value by assigning to value. The emit function is not available on MutableStateFlow. Also, StateFlow is an interface and cannot be instantiated directly.
You have two StateFlow<Int> instances: flowA and flowB. Which code snippet correctly creates a new StateFlow<Int> that always holds the sum of the latest values from flowA and flowB?
Think about how to combine two flows reactively and keep a StateFlow result.
The combine operator merges two flows and emits a new value whenever either changes. Using stateIn converts the combined flow into a StateFlow that holds the latest sum. zip waits for paired emissions and map with direct access to flowB.value is not reactive to changes in flowB. Creating a new MutableStateFlow with initial sum won't update automatically.