Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin runBlocking on background thread

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?

like image 753
Simone Avatar asked Jan 29 '19 14:01

Simone


People also ask

Does runBlocking block main thread?

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.

What is the best way for performing tasks on a background thread in Kotlin?

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.

How do I use runBlocking in Kotlin?

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.

When should I use runBlocking?

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.


1 Answers

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.

like image 173
Adib Faramarzi Avatar answered Oct 16 '22 23:10

Adib Faramarzi