Bird
Raised Fist0
Kotlinprogramming~20 mins

StateFlow for observable state in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
StateFlow Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this StateFlow example?

Consider this Kotlin code using StateFlow. What will be printed?

Kotlin
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()
}
A
Collected: 0
Collected: 1
Collected: 2
B
Collected: 0
Collected: 1
Collected: 1
Collected: 2
C
Collected: 0
Collected: 0
Collected: 1
Collected: 2
D
Collected: 1
Collected: 2
Attempts:
2 left
💡 Hint

Remember that StateFlow always emits the current value immediately to new collectors.

🧠 Conceptual
intermediate
1:30remaining
What happens when multiple collectors subscribe to the same StateFlow?

Given a StateFlow instance, what is true about multiple collectors?

AEach collector receives the current value immediately and all future updates independently.
BOnly the first collector receives updates; others get no values.
CCollectors share a single emission, so only one collector gets each update.
DCollectors receive values only if they subscribe before the first emission.
Attempts:
2 left
💡 Hint

Think about how StateFlow behaves like a hot stream that always holds the latest value.

🔧 Debug
advanced
2:30remaining
Why does this StateFlow collector never print updates?

Look at this Kotlin code snippet. Why does the collector never print any updates?

Kotlin
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)
}
AThe <code>collect</code> call is missing a coroutine scope, so it never starts.
BThe <code>stateFlow.value</code> assignment happens before <code>collect</code>, so no updates are printed.
CThe collector blocks the coroutine, so the value update never happens.
DThe <code>delay</code> is too short to allow collection to start.
Attempts:
2 left
💡 Hint

Consider how collect works in a coroutine and what happens after it.

📝 Syntax
advanced
1:30remaining
Which option correctly creates a StateFlow with initial value 5 and updates it to 10?

Choose the correct Kotlin code snippet that creates a MutableStateFlow with initial value 5 and then updates it to 10.

A
val stateFlow = StateFlow(5)
stateFlow.value = 10
B
val stateFlow = MutableStateFlow(5)
stateFlow.emit(10)
C
val stateFlow = MutableStateFlow&lt;Int&gt;(5)
stateFlow.value = 10
D
val stateFlow = MutableStateFlow(5)
stateFlow.value = 10
Attempts:
2 left
💡 Hint

Remember how to create and update a MutableStateFlow.

🚀 Application
expert
3:00remaining
How to combine two StateFlows to produce a new StateFlow with their sum?

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?

Aval sumFlow = MutableStateFlow(flowA.value + flowB.value)
Bval sumFlow = flowA.combine(flowB) { a, b -> a + b }.stateIn(scope, SharingStarted.Eagerly, 0)
Cval sumFlow = flowA.map { a -> a + flowB.value } as StateFlow<Int>
Dval sumFlow = flowA.zip(flowB) { a, b -> a + b }.stateIn(scope, SharingStarted.Lazily, 0)
Attempts:
2 left
💡 Hint

Think about how to combine two flows reactively and keep a StateFlow result.

Practice

(1/5)
1. What is the primary purpose of StateFlow in Kotlin?
easy
A. To handle exceptions in coroutines
B. To perform background network requests
C. To create immutable lists
D. To hold and emit observable state updates over time

Solution

  1. Step 1: Understand StateFlow's role

    StateFlow is designed to hold a value that can change and notify observers about these changes.
  2. Step 2: Compare with other options

    Options B, C, and D describe unrelated tasks like networking, immutable collections, or error handling, which are not StateFlow's purpose.
  3. Final Answer:

    To hold and emit observable state updates over time -> Option D
  4. Quick Check:

    StateFlow = observable state holder [OK]
Hint: StateFlow = observable state container for updates [OK]
Common Mistakes:
  • Confusing StateFlow with networking or error handling
  • Thinking StateFlow creates immutable collections
  • Assuming StateFlow is for one-time events
2. Which of the following is the correct way to declare a mutable StateFlow holding an integer with initial value 0?
easy
A. val state = StateFlow(0)
B. val state = mutableStateFlowOf(0)
C. val state = MutableStateFlow(0)
D. val state = StateFlow.Mutable(0)

Solution

  1. Step 1: Recall MutableStateFlow syntax

    MutableStateFlow is created by calling its constructor with an initial value, e.g., MutableStateFlow(0).
  2. Step 2: Check other options for syntax errors

    val state = StateFlow(0) uses StateFlow directly, which is an interface and cannot be instantiated. val state = mutableStateFlowOf(0) uses a non-existent function. val state = StateFlow.Mutable(0) uses invalid syntax.
  3. Final Answer:

    val state = MutableStateFlow(0) -> Option C
  4. Quick Check:

    MutableStateFlow constructor = MutableStateFlow(0) [OK]
Hint: Use MutableStateFlow(initialValue) to create mutable state [OK]
Common Mistakes:
  • Trying to instantiate StateFlow directly
  • Using incorrect function names like mutableStateFlowOf
  • Wrong syntax with dot notation on StateFlow
3. What will be printed by the following Kotlin code snippet?
val state = MutableStateFlow(10)

state.value = 20
println(state.value)
medium
A. 20
B. 10
C. null
D. Compilation error

Solution

  1. Step 1: Understand MutableStateFlow value update

    MutableStateFlow's value property can be updated directly. Here, state.value is set to 20.
  2. Step 2: Print the updated value

    Printing state.value after update will output 20, the new value.
  3. Final Answer:

    20 -> Option A
  4. Quick Check:

    state.value after update = 20 [OK]
Hint: state.value holds current value, prints updated value [OK]
Common Mistakes:
  • Expecting old value after update
  • Confusing value with collect() usage
  • Thinking it causes compilation error
4. Identify the error in this Kotlin code using StateFlow:
val state = MutableStateFlow(0)

fun updateState(newValue: Int) {
    state.emit(newValue)
}
medium
A. emit() cannot be called outside a coroutine
B. MutableStateFlow cannot hold integers
C. state should be declared as StateFlow, not MutableStateFlow
D. updateState must be a suspend function

Solution

  1. Step 1: Check usage of emit()

    emit() is a suspend function and must be called from a coroutine or suspend function.
  2. Step 2: Analyze function updateState

    updateState is a regular function, so calling emit() here causes a compile error.
  3. Final Answer:

    emit() cannot be called outside a coroutine -> Option A
  4. Quick Check:

    emit() requires coroutine context [OK]
Hint: emit() needs coroutine; can't call in normal function [OK]
Common Mistakes:
  • Calling emit() in non-suspend function
  • Confusing emit() with value assignment
  • Thinking MutableStateFlow can't hold Int
5. You want to create a Kotlin app state that updates a user's score and notifies UI reactively. Which approach correctly uses StateFlow to update and observe the score?
hard
A. Use a MutableStateFlow<Int> but update score only by calling collect
B. Use a MutableStateFlow<Int> for score, update with score.value = newScore, and collect changes in UI coroutine
C. Use a MutableStateFlow<Int> and update score by creating a new MutableStateFlow each time
D. Use a StateFlow<Int> and update with emit(newScore) in a regular function

Solution

  1. Step 1: Choose correct StateFlow type and update method

    MutableStateFlow allows updating the value property directly with score.value = newScore.
  2. Step 2: Observe changes properly in UI

    Collecting the StateFlow in a coroutine lets UI react to updates.
  3. Step 3: Eliminate incorrect options

    Use a StateFlow<Int> and update with emit(newScore) in a regular function wrongly calls emit() in a regular function. Use a MutableStateFlow<Int> and update score by creating a new MutableStateFlow each time recreates MutableStateFlow unnecessarily. Use a MutableStateFlow<Int> but update score only by calling collect misunderstands collect's role (it's for observing, not updating).
  4. Final Answer:

    Use a MutableStateFlow<Int> for score, update with score.value = newScore, and collect changes in UI coroutine -> Option B
  5. Quick Check:

    MutableStateFlow.value update + collect observation = correct [OK]
Hint: Update MutableStateFlow.value; collect in UI coroutine [OK]
Common Mistakes:
  • Calling emit() outside coroutine
  • Recreating MutableStateFlow instead of updating value
  • Confusing collect() as update method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard