Kotlin Coroutines: Fundamentals

Feb 14 2024 · Kotlin 1.9, Android 13, Android Studio Giraffe

Part 1: Getting started with Coroutines

03. Suspend Functions

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 02. Get Started with Kotlin Coroutines Next episode: 04. Challenge: Implement a Coroutine Calling Suspend Function

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 03. Suspend Functions

In this episode you’ll learn about suspending functions, the building blocks of coroutines. Let’s continue with the course! :]

Suspending is a way to pause a coroutine, and resume it later on.

Just like you can save a game at a checkpoint. You can then go back to that checkpoint later on.

You can have multiple checkpoints, and you can go back to any of them in any order.

The same rule also applies to coroutines. You can have hundreds of them, and resume whichever you want, whenever you want.

To make a function suspending, you need to add the suspend modifier to it.

Note that only functions or methods can be suspending. You can’t make a class suspending.

You can invoke the suspending function only from another suspending function, or from a coroutine builder.

If you try to invoke it from a regular function, you’ll get a compilation error.

Do you recall the suspending a function is like saving a game at a checkpoint?

Saved game is not running and does not consume any power. You can have hundreds of saved games, and they won’t affect the performance of your computer.

You can copy the saved game to another computer, and continue playing from the same checkpoint.

In case of coroutines we have the threads that are like computers.

A coroutine can resume on any thread meeting its requirements.

A suspending function cannot suspend anywhere. It can happen only on the suspension points.

Just like the game can be saved only at the checkpoints. But, not anywhere in the game.

The suspension points are the invocations of another suspending functions.

In Android Studio you can see the suspension points as arrow icons on the left side of the editor.

The delay() function suspends the coroutine for a specified amount of time.

Suspending on the delay() does not differ from suspending on any other point. It does not block underlying thread.

A coroutine waiting on delay() can be cancelled. In such case the delay() function throws an exception and the function execution continues to the nearest exception handler.

Oh well, that’s the end of theory for now.

In the next episode you’ll start coding!