0
0
Kotlinprogramming~30 mins

Coroutine scope and structured concurrency in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Coroutine scope and structured concurrency
📖 Scenario: You are building a simple Kotlin program that uses coroutines to perform tasks concurrently in a safe and organized way. This helps avoid problems like tasks running forever or leaking resources.
🎯 Goal: Learn how to create a CoroutineScope, launch coroutines inside it, and use structured concurrency to wait for all tasks to finish before ending the program.
📋 What You'll Learn
Create a CoroutineScope using runBlocking
Launch two coroutines inside the scope that print messages after delays
Use structured concurrency to wait for both coroutines to complete
Print a final message after all coroutines finish
💡 Why This Matters
🌍 Real World
Coroutines help write programs that do many things at once without freezing or crashing. This is useful in apps that load data, handle user input, or do background work.
💼 Career
Understanding coroutine scopes and structured concurrency is essential for Kotlin developers working on Android apps, backend services, or any system that needs efficient multitasking.
Progress0 / 4 steps
1
Create a CoroutineScope with runBlocking
Write a Kotlin program that creates a CoroutineScope using runBlocking. Inside it, write a comment // Coroutine scope started to mark the scope start.
Kotlin
Need a hint?

Use fun main() = runBlocking { } to create the coroutine scope.

2
Launch two coroutines inside the scope
Inside the runBlocking scope, launch two coroutines using launch. The first coroutine should delay 500 milliseconds and then print "First coroutine done". The second coroutine should delay 300 milliseconds and then print "Second coroutine done".
Kotlin
Need a hint?

Use launch { delay(500L); println("First coroutine done") } and similarly for the second coroutine.

3
Use structured concurrency to wait for coroutines
Modify the program so that the runBlocking scope waits for both launched coroutines to finish before continuing. Use the fact that launch returns a Job and call join() on both jobs.
Kotlin
Need a hint?

Save the result of launch in variables and call join() on them to wait.

4
Print a final message after all coroutines finish
After waiting for both coroutines to finish, print "All coroutines completed" inside the runBlocking scope.
Kotlin
Need a hint?

Use println("All coroutines completed") after joining both jobs.