Wrap the "inappropriate blocking method call" code in another context using withContext
.
That is to say (for example):
If you are doing a read/write blocking method call:
val objects = withContext(Dispatchers.IO) { dao.getAll() }
If you are performing a blocking network request (using Retrofit):
val response = withContext(Dispatchers.IO) { call.execute() }
Or if you are performing a CPU intensive blocking task:
val sortedUsers = withContext(Dispatchers.Default) { users.sortByName() }
This will suspend the current coroutine, then execute the "inappropriate blocking call" on a different thread (from either the Dispatchers.IO
or Dispatchers.Default
pools), thereby not blocking the thread your coroutine is executing on.