Appendix A. coroutines: Running Code in Parallel

image

  Some tasks are best performed in the background.

If you want to read data from a slow external server, you probably don’t want the rest of your code to hang around, waiting for the job to complete. In situations such as these, coroutines are your new BFF. Coroutines let you write code that’s run asynchronously . This means less time hanging around, a better user experience, and it can also make your application more scalable. Keep reading, and you’ll learn the secret of how to talk to Bob, while simultaneously listening to Suzy.

Let’s build a drum machine

Coroutines allow you to create multiple pieces of code that can run asynchronously. Instead of running pieces of code in sequence, one after the other, coroutines let you run them side-by-side.

Using coroutines means that you can launch a background job, such as reading data from an external server, without the rest of your code having to wait for the job to complete before doing anything else. This gives your user a more fluid experience, and it also makes your application more scalable.

To see the difference that using coroutines can make to your code, suppose you want to build a drum machine based on some code that plays a drum beat sequence. Let’s start by creating the Drum Machine project by going through the following steps.

The code in this appendix applies to Kotlin ...

Get Head First Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.