0
0
Kotlinprogramming~30 mins

SharedFlow for event broadcasting in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
SharedFlow for event broadcasting
📖 Scenario: You are building a simple event broadcaster in Kotlin using SharedFlow. This will allow multiple parts of your program to listen for and react to events like messages being sent.
🎯 Goal: Create a SharedFlow to broadcast string messages. Set up a simple event sender and a listener that prints received messages.
📋 What You'll Learn
Create a MutableSharedFlow of type String called eventFlow
Create a replay configuration with value 0 for eventFlow
Create a suspend function sendEvent that emits a message to eventFlow
Create a coroutine that collects from eventFlow and prints received messages
Send two messages using sendEvent and observe the output
💡 Why This Matters
🌍 Real World
SharedFlow is useful in apps where multiple parts need to react to events like user actions, notifications, or data updates.
💼 Career
Understanding SharedFlow helps you build responsive Kotlin applications with clean event handling, a skill valued in Android and backend development.
Progress0 / 4 steps
1
Create a MutableSharedFlow for events
Create a MutableSharedFlow of type String called eventFlow with replay = 0.
Kotlin
Need a hint?

Use MutableSharedFlow<String>(replay = 0) to create eventFlow.

2
Create a suspend function to send events
Create a suspend function called sendEvent that takes a String parameter message and emits it to eventFlow.
Kotlin
Need a hint?

Define sendEvent as a suspend function that calls eventFlow.emit(message).

3
Collect events and print them
Inside main, launch a coroutine that collects from eventFlow and prints each received message with println("Received: $message").
Kotlin
Need a hint?

Use launch to start a coroutine that calls eventFlow.collect and prints messages.

4
Send events and observe output
Inside main, call sendEvent(eventFlow, "Hello") and sendEvent(eventFlow, "World") to send two messages. Then add a small delay of 100 milliseconds to allow collection before main ends.
Kotlin
Need a hint?

Call sendEvent twice with messages "Hello" and "World" and add delay(100) to see output.