Basically, coroutines are computations that can be suspended without blocking a thread. To continue the analogy, await()
can be a suspending function (hence also callable from within an async {}
block) that suspends a coroutine until some computation is done and returns its result:
async { // Here I call it the outer async coroutine
...
// Here I call computation the inner coroutine
val result = computation.await()
...
}
We see await is called on computation, so it might be async that returns Deferred, which means it can start another coroutine
fun computation(): Deferred<Boolean> {
return async {
true
}
}
Does suspend mean that while outer async coroutine is waiting (await) for the inner computation coroutine to finish, it (the outer async coroutine) idles (hence the name suspend) and returns thread to the thread pool, and when the child computation coroutine finishes, it (the outer async coroutine) wakes up, takes another thread from the pool and continues? The thread is returned to the pool while the coroutine is waiting, and when the waiting is done, the coroutine resumes on a free thread in the pool.