Warning "Inappropriate blocking method call" with coroutines, how to fix?

Coroutines should never call blocking functions. The reason is simple, blocking functions block a thread and therefor stop any other coroutines to be executed on that thread. A better solution is to use suspending calls that just suspend the coroutine instead of blocking the thread (classic example is Thread.sleep vs delay).
But in reality there are a few functions that are blocking in nature, IO being one of the main examples. The way to solve this is by having a special dispatcher that can create as many threads as it needs. The problem with your scope executor is that it can at most use a single thread. So the first blocking call will block that thread, stopping all other coroutines as well because there is no thread to execute the coroutine.
The IO dispatcher on the other hand will just create an additional thread if all threads are used.
So the question now is “Why not use IO for everything?” Well, creating threads is expensive so you want to create as few as possible. If you were to create one thread for each coroutine you would tank your performance. The IO dispatcher is desinged specifically to handle blocking calls, while trying to minimize the performance overhead from creating additional threads, but also ensuring that you don’t run into deadlocks.

6 Likes