CodeBlanks Logo Icon CodeBlanks

Summary - Coroutine basics

Combine launch, suspend and async/await to write a parallel downloader.

Summary - Coroutine basics

In this group you learned the coroutine basics. A coroutine is a lightweight thread that can be suspended. launch starts a resultless coroutine, async starts a resultful one. suspend functions wait without blocking the thread.

runBlocking bridges the blocking world to the suspending world; it is used in main and tests. async/await brings parallel computation with synchronous-looking code. Each tool works inside structured concurrency; it prevents resource leaks and keeps code clean.

Choosing the right tool

Pick the tool for the job: launch for resultless start, async/await for resultful parallel work. Functions that need to wait are written as suspend. Use the runBlocking bridge in main or tests.

Structured concurrency binds every coroutine to a scope; child coroutines finish before the scope ends. This prevents resource leaks without explicit wait calls. Separating parallel and sequential work correctly yields both performance and deterministic output.

Practice Combine suspend and async/await

Add import kotlinx.coroutines.*. Define suspend fun fetch(): Int { delay(100); return 5 }. Write fun main() = runBlocking; inside call val a = async { fetch() } and println(a.await()).

Starter code

Main.kt
import kotlinx.coroutines.*

// Define the fetch suspend function: returns 5 after delay
// Call fetch with async in runBlocking and retrieve with await

Sample solution

Main.kt
import kotlinx.coroutines.*

suspend fun fetch(): Int {
    delay(100)
    return 5
}

fun main() = runBlocking {
    val a = async { fetch() }
    println(a.await())
}

Expected output

5

Practice Greet with runBlocking and suspend

Add import kotlinx.coroutines.*. Define suspend fun greet(name: String): String { delay(100); return "Hello, $name" }. Write fun main() = runBlocking { println(greet("Alex")) }.

Starter code

Main.kt
import kotlinx.coroutines.*

// Define the greet suspend function: returns a greeting after delay
// Call greet in runBlocking in main and print

Sample solution

Main.kt
import kotlinx.coroutines.*

suspend fun greet(name: String): String {
    delay(100)
    return "Hello, $name"
}

fun main() = runBlocking {
    println(greet("Alex"))
}

Expected output

Hello, Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which starts a resultless coroutine?

  • async
  • launch Correct answer
  • runBlocking
  • await

Explanation: launch starts fire-and-forget.

2 Match the coroutine tools

Term Meaning
launch Resultless start
async/await Resultful start
suspend Can pause
runBlocking Bridge

All lessons in Intermediate