From the course: Concurrent Programming with Android: Threads, Workers, and Kotlin Coroutines

Unlock this course with a free trial

Join today to access over 22,700 courses taught by industry experts.

Cancel coroutines with a job reference

Cancel coroutines with a job reference

- [narrator] When you launch a coroutine, the lunch function returns a reference to something called a job. And a job simply represents something that can be canceled. So once you have that reference, you can interrupt whatever work the coroutine is doing. You need to hold onto a reference to the job, though. So in my view model where I'm creating my coroutine, I'll add a new variable here. It'll be private to the class, and I'll use the lateinit var syntax, I'll name the variable job, and it'll be an instance of the job class from kotlinx.coroutines. Then I'll initialize that variable, when I launched the coroutine. I'll add job equals right before the launch command. Now I have my job reference. I'm going to create a new function that will be public, so it's available to the rest of the application, and it will be named Cancel Job. The code can be as simple as this, job dot cancel. There's an option to add an kotlinix…

Contents