CodeBlanks Logo Icon CodeBlanks

What are coroutines?

Learn the coroutine and async programming concept.

What are coroutines?

A coroutine is a lightweight thread that can suspend its work and resume later. A single thread can host thousands of coroutines with few resources; each coroutine takes a few hundred bytes.

Coroutines work with suspend functions: while waiting, they do not block the thread and let other work run. This replaces callback hell with clean code. The kotlinx.coroutines library provides tools like runBlocking, launch and async. In this lesson you will see the basic flow.

suspend and structured concurrency

A suspend function can pause and resume its work. While paused the thread is not blocked; other coroutines can run. delay is the simplest suspend function: it waits for a given time.

Structured concurrency ensures every coroutine has a scope. Child coroutines complete before the scope ends. This prevents resource leaks. runBlocking bridges the blocking world to the suspending world and waits for all coroutines inside.

Practice Run your first coroutine

Add import kotlinx.coroutines.*. Write fun main() = runBlocking { println("Hello coroutine") }. runBlocking opens a coroutine scope and blocks the main thread.

Starter code

Main.kt
import kotlinx.coroutines.*

// Define main with runBlocking and print

Sample solution

Main.kt
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Hello coroutine")
}

Expected output

Hello coroutine

Questions and answers

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

1 What is a coroutine?

  • A lightweight thread Correct answer
  • A heavy thread
  • A class type
  • A data structure

Explanation: A coroutine is a lightweight thread that can be suspended.

2 Complete the delay import

Question
import kotlinx.coroutines.____

suspend fun greet() { delay(100) }
Answer
import kotlinx.coroutines.delay

suspend fun greet() { delay(100) }

Explanation: delay is a suspend function.

3 Match the coroutine concepts

Term Meaning
coroutine Lightweight task
suspend Can pause
delay Wait
lightweight Few resources

All lessons in Intermediate