Home > Software engineering >  Android - what is Inappropriate blocking method call in Coroutine
Android - what is Inappropriate blocking method call in Coroutine

Time:08-24

enter image description here

I am studying kotlin now. Currently, after importing data from Room Database, I am using runBlocking to draw Layout, but there is a warning, so it is difficult to determine the cause. Help me

CodePudding user response:

  1. runBlocking should almost never be used in an Android app, and especially never in a coroutine. The only use case I can think of is if you are working with legacy code or a library that does not support use of coroutines, and you need to convert a suspend function into something that can be called by non-coroutine code in a background thread. This should be extremely rare, because it would be difficult to do correctly, and there are already functions in the Kotlin coroutines library for converting to and from Executors and Completables, etc, which would be simpler to use for this purpose.

  2. By convention, you must never have blocking code in a coroutine or suspend function unless it is wrapped in a CoroutineContext that uses a Dispatcher that can handle blocking code. See the Suspending Convention section in this article by the design lead of Kotlin coroutines. This is most commonly done using withContext(Dispatchers.Default) { } or withContext(Dispatchers.IO) { }

If you're using Room, you don't need to use blocking functions at all. You can define your DAO functions as suspend functions, and Room will automatically implement your functions so they won't block.

I'm not sure what you were trying to do with runBlocking. If your repo functions were blocking, runBlocking doesn't accomplish anything, and if they were suspending, you can call them directly in your coroutine.

  • Related