Kotlin - "Inappropriate Block Method Call" when making Bluetooth Connection inside Coroutine

Viewed 6384

I am getting a warning when I try to make a BT connection inside a coroutine.

I've checked this SO post, but it was only abstract theorycrafting and no material code. One of the answers there mentioned that the warning in the title should be dealt in a case-by-case basis, so here is my case. Does anyone know how I can resolve the warning? Thanks!

fun initSocket() = runBlocking {
    try {
        mSocket = // Assume socket is initialized correctly. Not relevant here
        mSocket.connect() // "Inapproprite Blocking Method Call"
        mOutputStream = mSocket.outputStream
    } catch (e: Exception) {
        Log.e(LOG_TAG, "Error establishing Socket Connection...")
    }
}
2 Answers

You are running entire thing inside runBlocking, which blocks the thread until it finishes. By the looks of it, you are calling it from the main thread, which is not allowed to make blocking calls - hence the error.

Instead of runBlocking, rather make suspend function using Dispathers.IO, to offload the connecting to an IO thread to avoid blocking main thread.

suspend fun initSocket() = withContext(Dispatchers.IO) { ... }

Your code doesn't actually contain any suspendable function calls. Simply remove runBlocking and you'll have the same blocking behavior that you have now.

If, by any chance, you do have some suspendable calls which you removed from your example as "irrelevant", then you should move the blocking call outside runBlocking and wrap only those suspendable calls in it.

Related