Deep look into Coroutine Suspend Functions. Part 1. Introduction
When you start reading official coroutines documentation, a lot of things are unclear: suspend functions, scopes, builders, dispatchers. In this article series I would like to have a deep look into one of these topics — Suspend Functions.
The series consists of 5 parts:
Let's take the example from official documentation:
Suspend function delay is used here. It may suspend execution of the code without blocking the current thread of execution. It might be not clear why we need it. To understand it better, we will get back to threads and synchronous, and asynchronous functions.
Let’s have a look at real life example — file downloading. Here is a respective code without any coroutines or suspend functions:
We build theURL, pass it to the function that will download the file and when the job is done we display the toast.
The download function is synchronous, therefore this code blocks the thread in which it is running. The toast function however requires it to be run on the UI thread. If we want to avoid blocking the UI thread, we can make the function asynchronous and use a callback:
We could also use other tools like RxJava, but in any case the code is getting more complicated and less readable. It would be great to have a function that can do a long running job without blocking thread and then continue executing the code without any callbacks or boilerplates.
Suspend function in coroutine is exactly what we could use here.
We changed the function download and now it is a suspend function (we will learn how to do it in one of the next articles). This coroutine doesn’t block the thread where it is run. So, we can execute it even on a UI thread. And toast will be displayed after downloading is completed.
It sounds like magic, but don’t forget that Kotlin code will be transformed to Java classes. During these transformations Continuation mechanism will be used, that plays the role of a callback for suspend function. In part two "How does Continuation work" we will have a look at this mechanism in details.