I'm in the process of converting an existing app from Java to Kotlin.
The app creates an IntentService which runs in a background thread and is tasked to perform some operations which block the thread (e.g. network calls, database interactions) with suspend
functions repeatedly and indefinitely.
Since the "current thread" is in fact a background thread I'm not blocking the UI.
Is it a good practice to make use of runBlocking
on the current thread to run all the suspending functions? Or there is a better approach?
This is why runBlocking with Dispatchers. Main blocks UI thread forever. The UI thread is blocked and waiting for the finishing targeted code. But it never finishes because the main looper can't start the targeted code.
So in your Kotlin programs, performing heavy operations like network calls, interacting with Database/Device file system, etc, etc. You need to execute those tasks in the background thread. That's means you should consider using the Asynchronous approach.
Definition of runBlocking() functionRuns a new coroutine and blocks the current thread interruptible until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
runBlocking() - use when you need to bridge regular and suspending code in synchronous way, by blocking the thread. Just don't overuse it. Don't treat runBlocking() as a quick fix for calling suspend functions.
That is exactly the usage of runBlocking
. runBlocking
was added to coroutines to create a bridge between the users of coroutines
and other places that are executing the code blockingly. If you want a thread to be blocked and wait for the execution of a a coroutine, you should always use runBlocking
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With