Bird
Raised Fist0
Kotlinprogramming~20 mins

SharedFlow for event broadcasting in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
SharedFlow 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 SharedFlow example?

Consider this Kotlin code using MutableSharedFlow to broadcast events. What will be printed?

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

fun main() = runBlocking {
    val sharedFlow = MutableSharedFlow<Int>()

    launch {
        sharedFlow.collect { value ->
            println("Collector 1 received: $value")
        }
    }

    launch {
        delay(100)
        sharedFlow.emit(1)
        sharedFlow.emit(2)
    }

    launch {
        delay(200)
        sharedFlow.collect { value ->
            println("Collector 2 received: $value")
        }
    }

    delay(500)
}
A
Collector 1 received: 1
Collector 1 received: 2
B
Collector 1 received: 1
Collector 1 received: 2
Collector 2 received: 1
Collector 2 received: 2
C
Collector 1 received: 1
Collector 1 received: 2
Collector 2 received: 2
D
Collector 2 received: 1
Collector 2 received: 2
Attempts:
2 left
💡 Hint

Think about when Collector 2 starts collecting and what events it can receive.

🧠 Conceptual
intermediate
1:30remaining
What happens if replay is set to 1 in MutableSharedFlow?

In MutableSharedFlow(replay = 1), what does the replay parameter do?

AIt limits the number of collectors to 1 at a time.
BIt caches the last emitted value and replays it to new collectors when they start collecting.
CIt buffers only one event and drops the rest if collectors are slow.
DIt delays emission of events by 1 millisecond.
Attempts:
2 left
💡 Hint

Think about what replay means in the context of event streams.

🔧 Debug
advanced
2:30remaining
Why does this SharedFlow code cause a deadlock?

Examine this Kotlin code snippet. Why does it cause the program to hang indefinitely?

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

fun main() = runBlocking {
    val sharedFlow = MutableSharedFlow<Int>(replay = 0, extraBufferCapacity = 0)

    launch {
        sharedFlow.emit(1)
        println("Emitted 1")
    }

    delay(100)

    sharedFlow.collect { value ->
        println("Collected: $value")
    }
}
ABecause extraBufferCapacity is zero, causing a buffer overflow error.
BBecause replay is zero, so no values are buffered and emit fails silently.
CBecause emit suspends until there is a collector ready, but no collector is active when emit is called.
DBecause collect is called after emit, so it misses all events and terminates immediately.
Attempts:
2 left
💡 Hint

Think about how emit behaves when there are no active collectors and no buffer.

📝 Syntax
advanced
1:30remaining
Which option correctly creates a MutableSharedFlow with replay 2 and buffer capacity 3?

Choose the correct Kotlin code to create a MutableSharedFlow with replay = 2 and extraBufferCapacity = 3.

Aval flow = MutableSharedFlow<Int>(replayCount = 2, bufferCapacity = 3)
Bval flow = MutableSharedFlow<Int>(bufferCapacity = 3, replayCount = 2)
Cval flow = MutableSharedFlow<Int>(replay = 3, extraBufferCapacity = 2)
Dval flow = MutableSharedFlow<Int>(replay = 2, extraBufferCapacity = 3)
Attempts:
2 left
💡 Hint

Check the official parameter names for MutableSharedFlow constructor.

🚀 Application
expert
3:00remaining
How to ensure all collectors receive all events in SharedFlow?

You want to broadcast events so that every collector receives all emitted events, even if they start collecting late. Which SharedFlow configuration achieves this?

AUse <code>MutableSharedFlow(replay = Int.MAX_VALUE)</code> to buffer all events indefinitely.
BUse <code>MutableSharedFlow(replay = 0, extraBufferCapacity = 0)</code> and start collectors before emitting.
CUse <code>MutableSharedFlow(replay = 1)</code> and emit events slowly to avoid loss.
DUse <code>MutableSharedFlow(replay = 0, extraBufferCapacity = Int.MAX_VALUE)</code> to buffer all events.
Attempts:
2 left
💡 Hint

Think about how replay buffers past events for new collectors.

Practice

(1/5)
1. What is the main purpose of SharedFlow in Kotlin?
easy
A. To broadcast events to multiple listeners simultaneously
B. To store data permanently in a database
C. To perform heavy computations asynchronously
D. To create a single-threaded event queue

Solution

  1. Step 1: Understand SharedFlow's role

    SharedFlow is designed to send events to many listeners at once, like a radio broadcast.
  2. Step 2: Compare with other options

    It does not store data permanently, perform heavy computations, or create single-threaded queues.
  3. Final Answer:

    To broadcast events to multiple listeners simultaneously -> Option A
  4. Quick Check:

    SharedFlow = Broadcast events [OK]
Hint: SharedFlow is like a radio sending to many listeners [OK]
Common Mistakes:
  • Confusing SharedFlow with data storage
  • Thinking SharedFlow handles computations
  • Assuming SharedFlow is single-threaded queue
2. Which of the following is the correct way to create a SharedFlow with replay of 2 events?
easy
A. val flow = SharedFlow<Int>(replayCount = 2)
B. val flow = MutableSharedFlow<Int>(replay = 2)
C. val flow = MutableSharedFlow<Int>(buffer = 2)
D. val flow = SharedFlow<Int>(bufferSize = 2)

Solution

  1. Step 1: Recall SharedFlow creation syntax

    MutableSharedFlow constructor uses parameter replay to set how many past events to keep.
  2. Step 2: Check options for correct parameter

    Only val flow = MutableSharedFlow<Int>(replay = 2) uses replay = 2 correctly. Others use wrong parameter names or types.
  3. Final Answer:

    val flow = MutableSharedFlow<Int>(replay = 2) -> Option B
  4. Quick Check:

    Use replay parameter to set past events [OK]
Hint: Use replay parameter in MutableSharedFlow constructor [OK]
Common Mistakes:
  • Using SharedFlow instead of MutableSharedFlow for creation
  • Wrong parameter names like bufferSize or replayCount
  • Confusing replay with buffer
3. What will be the output of this Kotlin code snippet?
val flow = MutableSharedFlow<Int>(replay = 1)

suspend fun main() {
    flow.emit(10)
    flow.emit(20)

    flow.collect { value ->
        println(value)
    }
}
medium
A. 10 20
B. 10
C. 20
D. No output

Solution

  1. Step 1: Understand replay behavior

    With replay = 1, only the last emitted value is kept for new collectors.
  2. Step 2: Analyze emitted values and collection

    Values 10 and 20 are emitted, but only 20 is replayed to the collector.
  3. Final Answer:

    20 -> Option C
  4. Quick Check:

    Replay 1 means last event only [OK]
Hint: Replay 1 means only last emitted event is received [OK]
Common Mistakes:
  • Expecting all emitted values to be replayed
  • Confusing replay with buffer size
  • Thinking collector receives events emitted before subscription
4. Identify the error in this Kotlin code using SharedFlow:
val flow = MutableSharedFlow<Int>()
suspend fun main() {
    flow.collect { println(it) }
    flow.emit(5)
}
medium
A. collect should be launched in a separate coroutine
B. emit must be called before collect
C. Calling emit after collect blocks the coroutine
D. MutableSharedFlow requires a replay parameter

Solution

  1. Step 1: Understand collect and emit behavior

    collect is a suspending function that waits for events and blocks until cancelled.
  2. Step 2: Analyze code flow

    Since collect is called first and blocks, emit is never reached. emit must be called concurrently.
  3. Final Answer:

    collect should be launched in a separate coroutine -> Option A
  4. Quick Check:

    collect blocks; emit needs separate coroutine [OK]
Hint: Run collect and emit in separate coroutines [OK]
Common Mistakes:
  • Calling emit after collect in same coroutine
  • Assuming emit runs before collect automatically
  • Thinking replay parameter is mandatory
5. You want to broadcast user click events to multiple UI components using SharedFlow. Which approach correctly ensures all components receive the latest 3 clicks even if they subscribe late?
hard
A. Use a simple List to store clicks and pass it to components on subscription
B. Use a MutableStateFlow to hold the last click and components read its value
C. Create a Channel with capacity 3 and send clicks; components receive from it
D. Create a MutableSharedFlow with replay = 3 and emit clicks; components collect from it

Solution

  1. Step 1: Identify replay requirement

    Replay of 3 means new subscribers get last 3 events automatically.
  2. Step 2: Match with SharedFlow usage

    MutableSharedFlow with replay = 3 fits perfectly for broadcasting recent events to multiple listeners.
  3. Step 3: Evaluate other options

    MutableStateFlow holds only one value, Channel does not replay past events, List is manual and not reactive.
  4. Final Answer:

    Create a MutableSharedFlow with replay = 3 and emit clicks; components collect from it -> Option D
  5. Quick Check:

    Replay 3 in SharedFlow broadcasts last 3 events [OK]
Hint: Use MutableSharedFlow with replay for recent event replay [OK]
Common Mistakes:
  • Using StateFlow which holds only one value
  • Using Channel which doesn't replay past events
  • Manually managing event lists instead of reactive streams
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