0
0
Kotlinprogramming~5 mins

Coroutine scope and structured concurrency in Kotlin

Choose your learning style9 modes available
Introduction

Coroutine scope helps manage coroutines by grouping them together. Structured concurrency makes sure coroutines finish properly and errors are handled safely.

When you want to run multiple tasks at the same time and keep track of them.
When you need to cancel all related tasks if one fails or if the user leaves a screen.
When you want to avoid memory leaks by automatically stopping coroutines when they are no longer needed.
When you want to organize your code so that background work is easy to control and understand.
Syntax
Kotlin
fun main() = runBlocking {
    launch {
        // coroutine work here
    }
}

runBlocking creates a coroutine scope that blocks the main thread until all coroutines inside finish.

launch starts a new coroutine inside the scope.

Examples
This example runs a coroutine that prints a message inside the main blocking scope.
Kotlin
fun main() = runBlocking {
    launch {
        println("Hello from coroutine")
    }
}
This example launches a coroutine that repeats work 3 times and waits for it to finish using join().
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        repeat(3) { i ->
            println("Coroutine working: $i")
            delay(100)
        }
    }
    job.join() // wait for coroutine to finish
}
This shows structured concurrency: the parent coroutine waits for its child coroutine before finishing.
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val parentJob = launch {
        launch {
            delay(100)
            println("Child coroutine done")
        }
        println("Parent coroutine done")
    }
    parentJob.join()
}
Sample Program

This program shows a main coroutine that launches a child coroutine. The main waits for the child to finish before ending.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Start main coroutine")

    val job = launch {
        println("Start child coroutine")
        delay(500)
        println("Child coroutine finished")
    }

    println("Waiting for child coroutine")
    job.join() // wait for child coroutine to finish
    println("Main coroutine finished")
}
OutputSuccess
Important Notes

Always use coroutine scopes to keep your coroutines organized and avoid leaks.

Structured concurrency means child coroutines are tied to their parent and cancel or complete together.

Use runBlocking only in main functions or tests; in apps, use lifecycle-aware scopes.

Summary

Coroutine scopes group coroutines to manage their lifecycle.

Structured concurrency ensures child coroutines finish before their parent.

This helps write safe, clear, and leak-free asynchronous code.