0
0
Kotlinprogramming~30 mins

FlowOn for changing dispatcher in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using FlowOn to Change Dispatcher in Kotlin Flow
📖 Scenario: You are building a simple Kotlin program that uses Flow to emit numbers. You want to change the thread where the flow runs using flowOn. This helps you run the flow on a background thread instead of the main thread.
🎯 Goal: Create a Kotlin Flow that emits numbers 1 to 3. Use flowOn to make the flow run on the Dispatchers.Default thread. Finally, collect and print the numbers on the main thread.
📋 What You'll Learn
Create a Flow that emits numbers 1, 2, and 3
Use flowOn(Dispatchers.Default) to change the dispatcher
Collect the flow and print each number
Use runBlocking to run the coroutine in main
💡 Why This Matters
🌍 Real World
Changing the dispatcher with flowOn is useful when you want to run heavy or blocking tasks on background threads without freezing the main UI thread.
💼 Career
Understanding flowOn is important for Kotlin developers working with asynchronous data streams and concurrency in Android or backend applications.
Progress0 / 4 steps
1
Create a Flow that emits numbers 1 to 3
Create a flow called numberFlow that emits the numbers 1, 2, and 3 using emit() inside the flow { } builder.
Kotlin
Need a hint?

Use val numberFlow = flow { emit(1); emit(2); emit(3) } to create the flow.

2
Add flowOn to change dispatcher to Dispatchers.Default
Add flowOn(Dispatchers.Default) to numberFlow to make it run on the Default dispatcher. Assign the result back to numberFlow.
Kotlin
Need a hint?

Use numberFlow = numberFlow.flowOn(Dispatchers.Default) or chain .flowOn(Dispatchers.Default) after the flow builder.

3
Collect the flow and print each number
Inside a runBlocking block, collect numberFlow using collect. For each emitted number, print it using println.
Kotlin
Need a hint?

Use runBlocking { numberFlow.collect { number -> println(number) } } to collect and print.

4
Print the collected numbers as output
Run the program and observe the printed numbers 1, 2, and 3 each on its own line.
Kotlin
Need a hint?

The program should print:
1
2
3