Search code examples
androidmultithreadingkotlinkotlinx.coroutines

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?


Solution

  • 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.