Coroutine Coding Quiz | theapache64
Skip to content

Coroutine Coding Quiz

Updated: at 12:00 AM

Test your Kotlin coroutine knowledge with this quiz! I’m planning to create multiple coroutine quizzes ranging from beginner to advanced levels. Each question has three choices in expandable sections, and you’ll need to click to reveal the answer and explanation.

Q1

What will be the output of this code?

fun main(args: Array<String>) {
    runBlocking {
        println("result is ${myFun()}")
    }
}

suspend fun myFun(): Int {
    return coroutineScope {
        var x = 0
        launch {
            delay(1000)
            x += 100
        }

        launch {
            delay(3000)
            x += 200
        }
        return@coroutineScope x
    }
}

Choices

Answer

Click to reveal the answer

Answer: result is 0

Explanation:

The key here is understanding how coroutineScope works with launch. The coroutineScope function waits for all child coroutines to complete before returning, BUT the output is 0 because the return@coroutineScope x statement executes immediately, before the delays in the launch blocks have finished.

Q2

What will be the output of this code

fun main(args: Array<String>) {
    runBlocking {
        repeat(4) { x ->
            println("${myFun(x)}")
        }
        println("done")
    }
}

suspend fun myFun(x: Int): Int = coroutineScope {
    val handler = CoroutineExceptionHandler { context, throwable ->
        println("caught")
    }
    return@coroutineScope async(handler + SupervisorJob()) {
        if (x == 2) {
            throw IOException("bhoom!")
        }
        x
    }.await()
}

Choices

Answer

Click to reveal the answer

Answer: 0, 1, process die with IOException

Explanation:

The async coroutines hold any exception occured within it and rethrown only when you call .await() or .awaitAll(). The attached CoroutineExceptionHandler won’t be triggered because the exception is already “caught” (and held) by the async block. In this case, since it’ll be rethrown outside handler scope, this will then propogate back and kill the process.

---