Bird
Raised Fist0
Android Kotlinmobile~5 mins

StateFlow and SharedFlow in Android Kotlin

Choose your learning style10 modes available
Introduction

StateFlow and SharedFlow help apps handle data that changes over time. They let your app react to updates smoothly and keep the user interface fresh.

When you want to show live data like user input or sensor updates.
When multiple parts of your app need to listen to the same data changes.
When you want to keep the latest state and share it safely across your app.
When you want to send one-time events like navigation commands or messages.
When you want to avoid manual callbacks and use a simple flow of data.
Syntax
Android Kotlin
val stateFlow = MutableStateFlow(initialValue)
val sharedFlow = MutableSharedFlow<T>(replay = 0)

StateFlow always holds the latest value and emits it to new collectors.

SharedFlow can emit events without holding a value, useful for one-time actions.

Examples
This creates a StateFlow holding an integer and updates its value.
Android Kotlin
val countState = MutableStateFlow(0)
countState.value = 1
This creates a SharedFlow for strings and emits a message event.
Android Kotlin
val eventFlow = MutableSharedFlow<String>()
launch { eventFlow.emit("Hello") }
This SharedFlow replays the last 2 emitted values to new collectors.
Android Kotlin
val replayFlow = MutableSharedFlow<Int>(replay = 2)
Sample App

This program shows how StateFlow keeps the latest number and SharedFlow sends events. Both are collected and printed.

Android Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
  val stateFlow = MutableStateFlow(0)
  val sharedFlow = MutableSharedFlow<String>()

  // Collect StateFlow
  val job1 = launch {
    stateFlow.collect { value ->
      println("StateFlow value: $value")
    }
  }

  // Collect SharedFlow
  val job2 = launch {
    sharedFlow.collect { event ->
      println("SharedFlow event: $event")
    }
  }

  // Update StateFlow
  stateFlow.value = 1
  delay(100)
  stateFlow.value = 2

  // Emit SharedFlow events
  sharedFlow.emit("First event")
  sharedFlow.emit("Second event")

  delay(100)
  job1.cancel()
  job2.cancel()
}
OutputSuccess
Important Notes

StateFlow always has a current value; SharedFlow does not have to hold a value.

Use StateFlow for state that changes over time and SharedFlow for events or messages.

Both flows are hot flows that share emissions with multiple collectors.

Summary

StateFlow holds and emits the latest state value.

SharedFlow emits events to multiple collectors without holding state.

Use them to build reactive and responsive Android apps easily.

Practice

(1/5)
1. What is the main difference between StateFlow and SharedFlow in Kotlin?
easy
A. Both StateFlow and SharedFlow hold the latest value.
B. StateFlow holds the latest value, SharedFlow does not hold any value.
C. SharedFlow holds the latest value, StateFlow does not hold any value.
D. Neither StateFlow nor SharedFlow hold any value.

Solution

  1. Step 1: Understand StateFlow behavior

    StateFlow always holds the latest emitted value and replays it to new collectors.
  2. Step 2: Understand SharedFlow behavior

    SharedFlow emits events but does not hold or replay the latest value by default.
  3. Final Answer:

    StateFlow holds the latest value, SharedFlow does not hold any value. -> Option B
  4. Quick Check:

    StateFlow holds state, SharedFlow emits events [OK]
Hint: Remember: StateFlow = state holder, SharedFlow = event emitter [OK]
Common Mistakes:
  • Thinking SharedFlow holds the latest value like StateFlow
  • Confusing event emission with state holding
  • Assuming both behave the same way
2. Which of the following is the correct way to create a StateFlow with an initial value of 0?
easy
A. val stateFlow = StateFlow<Int>()
B. val stateFlow = MutableSharedFlow(0)
C. val stateFlow = MutableStateFlow(0)
D. val stateFlow = SharedFlow(0)

Solution

  1. Step 1: Identify correct constructor for StateFlow

    MutableStateFlow requires an initial value and is created with MutableStateFlow(initialValue).
  2. Step 2: Check other options

    MutableSharedFlow does not take an initial value; StateFlow is an interface and cannot be instantiated directly.
  3. Final Answer:

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

    MutableStateFlow needs initial value [OK]
Hint: StateFlow needs initial value via MutableStateFlow constructor [OK]
Common Mistakes:
  • Trying to instantiate StateFlow interface directly
  • Using SharedFlow constructor for StateFlow
  • Passing initial value to MutableSharedFlow
3. Given the code below, what will be printed?
val stateFlow = MutableStateFlow(10)

stateFlow.value = 20

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

Solution

  1. Step 1: Understand MutableStateFlow value assignment

    Assigning stateFlow.value = 20 updates the current value held by the StateFlow.
  2. Step 2: Print the current value

    println(stateFlow.value) prints the latest value, which is 20.
  3. Final Answer:

    20 -> Option D
  4. Quick Check:

    StateFlow.value reflects latest assigned value [OK]
Hint: StateFlow.value always shows latest assigned value [OK]
Common Mistakes:
  • Thinking initial value 10 will print instead of updated 20
  • Confusing StateFlow with SharedFlow behavior
  • Expecting null or error due to reassignment
4. What is wrong with this code snippet using SharedFlow?
val sharedFlow = MutableSharedFlow<Int>()

sharedFlow.value = 5
medium
A. SharedFlow does not have a value property to assign.
B. You must initialize SharedFlow with an initial value.
C. You cannot create a MutableSharedFlow without parameters.
D. The code is correct and will compile.

Solution

  1. Step 1: Check SharedFlow properties

    SharedFlow does not hold state and has no value property to assign.
  2. Step 2: Understand how to emit values

    Values are emitted using emit() or tryEmit() functions, not by assigning value.
  3. Final Answer:

    SharedFlow does not have a value property to assign. -> Option A
  4. Quick Check:

    SharedFlow emits events, no value property [OK]
Hint: Use emit() to send values in SharedFlow, not value assignment [OK]
Common Mistakes:
  • Trying to assign value property on SharedFlow
  • Confusing SharedFlow with StateFlow
  • Assuming SharedFlow holds state like StateFlow
5. You want to create a SharedFlow that replays the last 3 emitted values to new collectors. Which configuration is correct?
hard
A. val sharedFlow = MutableSharedFlow<Int>(replay = 3)
B. val sharedFlow = MutableSharedFlow<Int>(replay = 0)
C. val sharedFlow = MutableStateFlow<Int>(3)
D. val sharedFlow = MutableSharedFlow<Int>(bufferSize = 3)

Solution

  1. Step 1: Understand replay parameter in SharedFlow

    The replay parameter defines how many past values are replayed to new collectors.
  2. Step 2: Check options for replaying last 3 values

    Setting replay = 3 in MutableSharedFlow correctly configures this behavior.
  3. Final Answer:

    val sharedFlow = MutableSharedFlow<Int>(replay = 3) -> Option A
  4. Quick Check:

    Replay count sets how many past events are replayed [OK]
Hint: Use replay parameter to replay past events in SharedFlow [OK]
Common Mistakes:
  • Confusing bufferSize with replay
  • Using StateFlow instead of SharedFlow for replay
  • Setting replay to 0 expecting replay behavior
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