Thuta Learning
AdvancedProgrammingbeginner

Advanced Kotlin Coroutines

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Write a suspending function
  • Tell launch and async apart
  • Understand structured concurrency

Let's break it down simply

A coroutine is a computation that can suspend and resume without blocking a thread. suspend marks a function as able to suspend, and kotlinx.coroutines provides launch, async, and dispatchers. Keeping child coroutines within a scope makes cancellation and error handling predictable.

kotlin
import kotlinx.coroutines.*

suspend fun fetchName(): String {
    delay(200)
    return "Mya"
}

suspend fun fetchScore(): Int {
    delay(200)
    return 91
}

suspend fun main() = coroutineScope {
    val name = async { fetchName() }
    val score = async { fetchScore() }
    println("${name.await()}: ${score.await()}")
}
You should see
Mya: 91

Try it yourself

Run two separate suspend functions concurrently with async and collect their results with awaitAll.

Coroutines BasicsKotlin

Easy traps

  • Blocking the thread by using Thread.sleep inside a coroutine
  • Using lifecycle-less GlobalScope in regular app code

Exercise

Run two separate suspend functions concurrently with async and collect their results with awaitAll.

You'll know it worked when: Mya: 91

Advanced Kotlin Coroutines | Thuta Learning