Chapter 8. Structured Concurrency with Coroutines
In the previous chapter, we introduced a new asynchronous programming paradigm—coroutines. When using coroutines, it’s important to know how to use suspending functions appropriately; we’ll cover that topic in this chapter. As most programs have to deal with exception handling and cancellation, we’ll also cover these topics—and you’ll see that, in this regard, coroutines have their own set of rules you should be aware of.
The first section of this chapter covers the idiomatic usage of suspending functions. We’ll take the example of a hiking app to compare two implementations: one based on threads and the other one based on suspending functions and coroutines. You’ll see how this comparison highlights the power of coroutines in some situations.
As is common for most mobile apps, the hiking example requires a cancellation mechanism. We’ll cover all you need to know about cancellation with coroutines. In order to prepare for most situations, we’ll then cover parallel decomposition and supervison. Using these concepts, you’ll be able to implement complex concurrent logic if you need to.
Finally, this chapter ends with an explanation of exception handling with coroutines.
Suspending Functions
Imagine that you’re developing an application to help users plot, plan, track, draw, and share information about hiking. Your users should be able to navigate to any of the hikes they’ve already completed or that are in progress. Before going ...
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.