Bird
Raised Fist0
Kotlinprogramming~20 mins

Why coroutines matter for async programming in Kotlin - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Coroutine Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this coroutine example?

Consider this Kotlin coroutine code snippet. What will it print?

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(100L)
        println("World!")
    }
    println("Hello,")
}
AHello,\nWorld!
BWorld!\nHello,
CHello, World!
DCompilation error
Attempts:
2 left
💡 Hint

Remember that launch starts a coroutine that runs concurrently, and delay suspends it without blocking the main thread.

🧠 Conceptual
intermediate
2:00remaining
Why are coroutines preferred over threads for async tasks?

Which reason best explains why coroutines are preferred over traditional threads for asynchronous programming in Kotlin?

ACoroutines run on separate CPU cores automatically, unlike threads.
BCoroutines do not require any scheduler to run, unlike threads.
CCoroutines can only run synchronously, making them simpler than threads.
DCoroutines are lightweight and use less memory than threads, allowing many to run concurrently without heavy resource use.
Attempts:
2 left
💡 Hint

Think about resource use and how many tasks you can run at once.

🔧 Debug
advanced
2:00remaining
Identify the runtime error in this coroutine code

What runtime error will this Kotlin coroutine code produce?

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        delay(1000L)
        println("Task finished")
    }
    job.cancel()
    println("Job cancelled")
}
ACancellationException thrown and program crashes
BNo error; output is 'Job cancelled' only
CDeadlock occurs and program hangs
DCompilation error due to missing try-catch
Attempts:
2 left
💡 Hint

Consider what happens when you cancel a coroutine job before it finishes.

📝 Syntax
advanced
2:00remaining
Which option correctly launches a coroutine with a delay?

Which Kotlin code snippet correctly launches a coroutine that waits 500ms and then prints "Done"?

A
launch {
    delay(500)
    println("Done")
}
B
launch {
    Thread.sleep(500L)
    println("Done")
}
C
launch {
    delay(500L)
    println("Done")
}
D
launch {
    delay(500L)
    print("Done")
}
Attempts:
2 left
💡 Hint

Check the delay parameter type and the print function used.

🚀 Application
expert
2:00remaining
How many coroutines run concurrently in this example?

Given this Kotlin code, how many coroutines run concurrently?

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    repeat(3) {
        launch {
            delay(100L * it)
            println("Coroutine $it done")
        }
    }
}
A3 coroutines run concurrently
BOnly 1 coroutine runs at a time sequentially
C2 coroutines run concurrently
DNo coroutines run because of delay
Attempts:
2 left
💡 Hint

Think about how launch and repeat work together.

Practice

(1/5)
1. Why are coroutines important for asynchronous programming in Kotlin?
easy
A. They allow tasks to run without blocking the main thread.
B. They make the code run slower but safer.
C. They replace all functions with loops.
D. They force the program to wait for each task to finish.

Solution

  1. Step 1: Understand asynchronous programming

    Asynchronous programming means running tasks without stopping the main program flow.
  2. Step 2: Role of coroutines in Kotlin

    Coroutines let tasks run in the background without blocking the main thread, improving responsiveness.
  3. Final Answer:

    They allow tasks to run without blocking the main thread. -> Option A
  4. Quick Check:

    Coroutines = non-blocking tasks [OK]
Hint: Coroutines keep the app responsive by not blocking main thread [OK]
Common Mistakes:
  • Thinking coroutines slow down the program
  • Confusing coroutines with loops
  • Believing coroutines force waiting
2. Which of the following is the correct way to start a coroutine in Kotlin?
easy
A. startCoroutine { println("Hello") }
B. run { println("Hello") }
C. launch { println("Hello") }
D. beginCoroutine { println("Hello") }

Solution

  1. Step 1: Recall coroutine builders in Kotlin

    The common builder to start a coroutine is launch.
  2. Step 2: Check syntax correctness

    launch { ... } is valid, while others like startCoroutine or beginCoroutine are not standard coroutine starters.
  3. Final Answer:

    launch { println("Hello") } -> Option C
  4. Quick Check:

    Use launch to start coroutine [OK]
Hint: Remember: launch is the coroutine starter function [OK]
Common Mistakes:
  • Using non-existent coroutine functions
  • Confusing run with launch
  • Trying to start coroutine without a builder
3. What will be the output of this Kotlin code using coroutines?
import kotlinx.coroutines.*
fun main() = runBlocking {
  launch {
    delay(100)
    println("World")
  }
  println("Hello")
}
medium
A. World\nHello
B. Hello\nWorld
C. Hello
D. World

Solution

  1. Step 1: Understand runBlocking and launch

    runBlocking blocks main thread until all coroutines inside finish. launch starts a coroutine that delays 100ms before printing.
  2. Step 2: Trace execution order

    "Hello" prints immediately. After 100ms delay, "World" prints. So output is "Hello" then "World".
  3. Final Answer:

    Hello World -> Option B
  4. Quick Check:

    Immediate print then delayed print = Hello then World [OK]
Hint: Immediate prints appear before delayed ones [OK]
Common Mistakes:
  • Assuming launch blocks main thread
  • Expecting World before Hello
  • Ignoring delay effect
4. Identify the error in this Kotlin coroutine code:
fun main() {
  launch {
    println("Running")
  }
}
medium
A. launch requires a delay before printing.
B. println cannot be used inside launch.
C. main function must be suspend to use launch.
D. launch must be called inside a coroutine scope or suspend function.

Solution

  1. Step 1: Check coroutine context requirements

    launch needs a coroutine scope or suspend function to run properly.
  2. Step 2: Analyze main function usage

    Here, launch is called directly in main without a scope, causing an error.
  3. Final Answer:

    launch must be called inside a coroutine scope or suspend function. -> Option D
  4. Quick Check:

    launch needs coroutine scope [OK]
Hint: launch always needs a coroutine scope or suspend context [OK]
Common Mistakes:
  • Thinking println is invalid inside launch
  • Believing main must be suspend always
  • Adding unnecessary delay
5. You want to fetch user data and user posts asynchronously in Kotlin using coroutines, then combine results. Which approach is best?
hard
A. Use async for both tasks and await their results before combining.
B. Use two separate launch blocks and combine results after both finish.
C. Run both tasks sequentially in the main thread.
D. Use delay to wait between fetching user data and posts.

Solution

  1. Step 1: Understand async vs launch

    async returns a deferred result you can await; launch is for fire-and-forget tasks.
  2. Step 2: Combining asynchronous results

    Using async for both tasks lets you start them concurrently and then await both results to combine efficiently.
  3. Final Answer:

    Use async for both tasks and await their results before combining. -> Option A
  4. Quick Check:

    async + await = concurrent results combined [OK]
Hint: Use async to get results you need to combine [OK]
Common Mistakes:
  • Using launch when results are needed
  • Running tasks sequentially wasting time
  • Using delay instead of proper async control
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard