Kotlin Coroutines: Fundamentals

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

Part 1: Getting started with Coroutines

04. Challenge: Implement a Coroutine Calling Suspend Function

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: 03. Suspend Functions Next episode: 05. Understand Coroutine Context & Dispatchers

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: 04. Challenge: Implement a Coroutine Calling Suspend Function

Now that you’ve learned about the basics of coroutines, it’s time to put them to use! You’ll implement your first coroutine. Open your IDE and let’s get started!

Clone the repository from the “Download materials” link in the main page of this course, and open the starter project in Android Studio.

Navigate to the ScopesScreen file.

You can find a suspend function called navigateBackDelayed(). It waits 2 seconds, and then tries to navigate back to the previous screen.

There is also a simple composable with 2 buttons in a column there.

Look at the “Navigate back in composable scope” button.

Your task is to call the navigateBackDelayed() function in a coroutine started on each button click.

Tip: use the existing coroutineScope and one of the coroutine builders you’ve learned about in the previous episode.

Now, let’s see how you did! Compare your solution with the one in the final project.

The correct builder here is launch. There is no need to return any result from the coroutine so async is not necessary.

It will work, but you’ll get a warning that the Deferred result is not used.

Note the scope obtained by the rememberCoroutineScope() function from the Jetpack Compose library. It’s a scope bound to the lifecycle of the composable.

That scope, and its coroutines will be cancelled when the composable is no longer on the screen.

So if you navigate away from the screen before the 2 seconds pass, the back navigation won’t happen.

Run the sample app and try it out!

As you can see, there is no “navigating back” message in the logs. That’s because the coroutine was cancelled when the composable left the composition.

In the next episode you’ll learn about the coroutine context and dispatchers.