Chapter 7. Coroutines Concepts
In the previous chapter, you learned of the pitfalls of the threading model. As an alternative to the threading model, the Kotlin language has a library called kotlinx.coroutines which aims at fixing the previously mentioned limitations. Coroutine-enabled primitives allow developers to write sequential, asynchronous code at a low cost. The design of coroutines comprises suspending functions, structured concurrency, and other specific considerations like coroutine context and coroutine scope. The subjects are closely related to one another. We’ll cover each one of these considerations in a way that is incremental and digestible.
What Exactly Is a Coroutine?
The official Kotlin documentation qualifies coroutines as “lightweight threads” in an effort to leverage an existing and well-known paradigm. You may conceptualize coroutines as blocks of code that can be dispatched to threads that are nonblocking.
Coroutines are indeed lightweight, but it is important to note that coroutines aren’t threads themselves. In fact, many coroutines can run on a single thread, although each has a lifecycle of its own. Rather, you’ll see in this section that they really are just state machines, with each state corresponding to a block of code that some thread will eventually execute.
Note
You might be surprised to find that the concept of coroutines goes all the way back to the early 1960s with the creation of Cobol’s compiler, which used the idea of suspending and launching ...
Get Programming Android with Kotlin now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.