top of page

Do you know what “coroutines are cooperative” means? 🤔




As promised, this is the answer to the challenge I posted 4 days ago 🧩 (sorry I was a bit late this time).


Congratulations 🎉 to everyone who got it right, and thank you for the explanations! I’ll mention everyone in the comments.


As usual, before I explain the answer - go ahead and take a look at the video 🎥.


This example was a bit tricky to build because there are so many moving parts. I tried to reflect a simplified version of what’s happening “under the hood” in the UI.


If you want to take a “deep dive” 🤿 and play around with the code - it’s here


Now, the explanation:


As you can see in the video, we’re playing through 3 scenarios. Let’s start with the first one:


In the first part, we’re launching an “uncooperative” coroutine and trying to stop it. As you can see - this doesn’t help 🚫.


Therefore, we need to break the loop for the coroutine to stop doing what it’s doing.


Let’s understand why this coroutine doesn’t stop.


For your coroutine to be canceled, it has to “cooperate.” In other words, you have to give the framework the ability to somehow cancel your coroutine.


This can be done in 2 ways:


1️⃣ Proactively check if the coroutine isActive. Coroutines have a lifecycle. They can have 3 states: Active, Cancelled and Completed.


If your coroutine was canceled - it’s no longer in the “Active” stage.


This means if we check for isActive we can finally quit the execution of the coroutine.


2️⃣ Another approach is to throw a CancellationException. You can throw it yourself by doing “throw CancellationException().”


Or you can use a function that will do it for you - like in our example. The delay() suspending function automatically detects if the coroutine was canceled and throws the exception for us.


Functions like delay(), withTimeout(), join() and await() all throw CancellationExceptions 🛑.


This was a very short overview of coroutine cooperation. I hope you enjoyed this example.


What is your experience with working coroutine cooperation in Kotlin? Share your experiences below👇.

62 views0 comments

Recent Posts

See All

Comments


bottom of page