Coroutines Under the Hood Interview Questions

KOTLIN › Coroutines

How does suspend work under the hood? What does the compiler turn a suspend function into?

What a strong answer covers: The compiler applies continuation-passing style: each suspend function gets an extra Continuation parameter and returns Any? (either the result or the COROUTINE_SUSPENDED marker). The body becomes a state machine: local variables are saved in the continuation object, and a label records which suspension point to resume from. When the awaited work finishes it calls continuation.resumeWith(result), which re-enters the function at the right label.

What is a Continuation, and what is a CoroutineContext made of?

What a strong answer covers: A Continuation holds the state needed to resume a suspended coroutine and a resumeWith(Result) method. CoroutineContext is an indexed set of elements: Job (lifecycle and cancellation), CoroutineDispatcher (which thread), CoroutineName, and CoroutineExceptionHandler. Elements combine with +, and a child inherits its parent's context but gets a new Job.

How would you wrap a callback-based API so it can be called as a suspend function?

What a strong answer covers: Use suspendCancellableCoroutine { cont -> api.request(object : Callback { onSuccess(r) = cont.resume(r); onError(e) = cont.resumeWithException(e) }); cont.invokeOnCancellation { call.cancel() } }. Use the cancellable version so cancellation propagates to the underlying call, and never resume twice. For streams of callbacks, use callbackFlow instead.

Why are coroutines described as cheap, and are there costs that people miss?

What a strong answer covers: A suspended coroutine is a small heap object holding its state machine and locals, no thread stack, so you can have hundreds of thousands. Costs people miss: each suspend call allocates a continuation if it actually suspends, dispatching to another dispatcher costs a context switch, deep suspend call chains add overhead, and long-running blocking code still occupies a real thread. Coroutines make waiting cheap, not computation.

How does a dispatcher actually resume a coroutine on the main thread, and what does the Main dispatcher do with Android's Looper?

What a strong answer covers: When a continuation resumes, the DispatchedContinuation asks its dispatcher whether it needs to dispatch; if so, it wraps the resume in a Runnable and calls dispatch(). The Android Main dispatcher (HandlerContext) posts that Runnable to a Handler on the main Looper, and Main.immediate skips the post when already on the main thread. So coroutine work on Main is just messages in the same queue as input and drawing, which is why long work on Main still janks.

Back to Coroutines Under the Hood