1. Overview

In this tutorial, we’re going to understand the warning “inappropriate blocking method call”.

We’ll learn why the IDE gives us that warning by first writing an inappropriate call and then what steps we can take to make an appropriate call.

2. Creating an Inappropriate Blocking Method Call

An inappropriate blocking method call is a call to a function that blocks the current Thread while inside a CoroutineContext. Coroutines allow us to create asynchronous programs fluently. Mixing their asynchronicity with a Thread that blocks removes the benefits that coroutines have to offer.

Let’s start by using Thread.sleep() to create a blocking call inside a suspend function:

suspend fun sleepThread() {
    Thread.sleep(100L)
}

We’ll get the warning from our IDE as expected:

Possibly blocking call in non-blocking context could lead to thread starvation

3. Fixing an Inappropriate Blocking Method Call

To turn an inappropriate call into an appropriate one, we must bring the non-coroutine blocking call to the coroutine world. When we’re in suspendable functions, we can use withContext to tell the coroutine engine which Dispatcher we want it to use. The only way to escape this situation is to wrap the blocking code in the IO Dispatcher:

suspend fun sleepThread() {
    withContext(Dispatchers.IO) {
        Thread.sleep(100L)
    }
}

4. Conclusion

In this tutorial, we learned what an inappropriate blocking method call in a Kotlin suspend function is and how to handle it with withContext and Dispatchers.IO. As always, all the code used in this tutorial is available over on GitHub.