Coroutines Basics Interview Questions
KOTLIN › Coroutines
What is a coroutine, and how is it different from a thread?
What a strong answer covers: A coroutine is a suspendable computation managed by the Kotlin runtime, not the OS. Thousands can run on a few threads because suspending frees the thread instead of blocking it. Threads are OS-scheduled, expensive (about 1 MB of stack each) and block while waiting. Coroutines also bring structured concurrency: cancellation and errors flow through a parent-child hierarchy.
What is the difference between launch and async? When would you use runBlocking?
What a strong answer covers: launch starts fire-and-forget work and returns a Job; async returns a Deferred whose await() gives a result, used to run things concurrently and combine results. runBlocking blocks the current thread until its coroutines finish; it bridges blocking code to coroutines in main functions and tests, and should never be called on the main thread in an app.
What does the suspend keyword actually mean? Does marking a function suspend make it run on a background thread?
What a strong answer covers: suspend means the function can pause without blocking its thread and can only be called from a coroutine or another suspend function. It does not move work off the current thread: a suspend function doing CPU work or blocking I/O on Main still blocks Main. Main-safety comes from withContext(Dispatchers.IO or Default) inside the function.
Walk me through what happens when viewModelScope.launch calls a suspend network function and the user rotates the screen.
What a strong answer covers: launch returns immediately and schedules the block on Dispatchers.Main.immediate. At the network call the coroutine suspends and frees the main thread; Retrofit's suspend support does the call on its own threads. On rotation the Activity is recreated but the ViewModel survives, so viewModelScope and the coroutine carry on; when the result arrives it resumes on Main and updates state, which the new UI collects. Only when the ViewModel is cleared is the scope cancelled.
When does async with an immediate await add nothing, and how would you load three independent API calls concurrently and fail cleanly if one fails?
What a strong answer covers: async { }.await() straight away is just a slower direct call; async only helps when you start several before awaiting. For three calls: coroutineScope { val a = async { api.a() }; val b = async { api.b() }; val c = async { api.c() }; Result(a.await(), b.await(), c.await()) }. If one throws, coroutineScope cancels the others and rethrows. If partial results are acceptable, use supervisorScope and catch around each await.