Coroutines do š”š¢š§ automatically run computations in the background!
- Nikolay Miroshnychenko

- Aug 31, 2024
- 2 min read
One worrying thing Iāve noticed during the recent interviews Iāve been conducting is devs thinking that starting a coroutine == starting a new thread.
Spoiler - they donāt.
So what's the confusion?
It seems like the maintainers of Room and Retrofit libraries have done such a good job of being good threading ācitizensā that some developers have forgotten about threading altogether. I was today years old when I found out that you can call Retrofit and Room suspending functions straight from the main thread.
Devs these days donāt know how good they have it. Back in the old days, we had to use Async Tasks after walking 10 miles in the snow blizzard.
Anyway, I built this example to demonstrate what can happen when you run coroutines without specifying the dispatcher.
As I mentioned previously, it seems like people are forgetting we can have blocking functions in our code. Besides Retrofit and Room, there are still things like writing files to memory, data encryption, and image processing that are thread-blocking and donāt provide suspending APIs (not yet at least).
Many people asked me why I included šššššš.ššššš() in the example. I did it specifically to demonstrate a blocking operation. If you donāt specify a dispatcher for your coroutine - it will run the blocking operation on the thread from which you invoked it. And this can stall your application. If this was a network request - we would get the infamous š½ššš šššš¾šš¼šššššššššš“š”ššššššš .
The main thing to remember here is that coroutines use threads. Youāre not creating a thread when youāre launching a coroutine. Each newly created coroutine will run on the same thread as the previous coroutine (if you donāt specify otherwise). Even though coroutines run concurrently - you can still block the thread youāre running it on.
Everything inside a coroutine is executed sequentially. If the next operation in your coroutine is blocking (like šššššš.ššššš()) - you will block the crap out of the underlying thread.
If you look at step #5 in the example - you see that the operations are executing āat the same timeā.Ā In step #5 both coroutines are running concurrently - so itās up to the processor to decide which instruction will run next. But what we DĶOĶ know is that even if ššššš¢(š»š¶š¶) runs first - it will āreleaseā the thread and weāll block it with šššššš.ššššš() either way for a whole second.
So there you have it, folks. Remember that a coroutine is just a mechanism to manipulate threads - itās the threads that do the heavy lifting - coroutines simply take all the glory.






Comments