Kotlin Kotlin Coroutines 2 — Questions and Answers
Question 1: What does calling `cancel()` on a Job do in Kotlin coroutines?
- Pauses the coroutine
- Cancels the coroutine and all its children (Correct answer)
- Restarts the coroutine
- Throws a CancellationException immediately
Correct answer: Cancels the coroutine and all its children
Calling `cancel()` on a `Job` requests cancellation of the coroutine and all coroutines launched in its scope.
Question 2: Which function suspends a coroutine for a given duration in Kotlin?
- Thread.sleep()
- wait()
- delay() (Correct answer)
- pause()
Correct answer: delay()
`delay()` is a suspending function that pauses a coroutine for a specified time without blocking the underlying thread.
Question 3: What is structured concurrency in Kotlin coroutines?
- Running coroutines in sequence only
- Ensuring child coroutines are scoped to a parent and cancelled together (Correct answer)
- Using only GlobalScope for all coroutines
- Limiting the number of concurrent coroutines
Correct answer: Ensuring child coroutines are scoped to a parent and cancelled together
Structured concurrency ensures that coroutines are launched within a defined scope, so child coroutines are automatically cancelled if the parent scope is cancelled.
Question 4: What is a Flow in Kotlin coroutines?
- A single suspending value
- A cold asynchronous data stream that emits multiple values (Correct answer)
- A thread pool manager
- A coroutine dispatcher
Correct answer: A cold asynchronous data stream that emits multiple values
A `Flow` is a cold asynchronous stream that emits multiple values sequentially, similar to Sequences but with suspend support.
Question 5: Which terminal operator collects all emitted values from a Flow?
- emit()
- produce()
- collect() (Correct answer)
- receive()
Correct answer: collect()
`collect()` is a suspending terminal operator that collects all values emitted by a Flow and processes them.
Question 6: What happens when a coroutine throws an uncaught exception?
- The exception is silently ignored
- The coroutine pauses and waits
- The exception propagates to the parent scope and cancels it (Correct answer)
- The JVM crashes immediately
Correct answer: The exception propagates to the parent scope and cancels it
An uncaught exception in a coroutine propagates up the job hierarchy, cancelling the parent scope unless a `SupervisorJob` is used.
What does calling `cancel()` on a Job do in Kotlin coroutines?