Home > Software design >  Coroutines and suspend related to main thread and dispatcher
Coroutines and suspend related to main thread and dispatcher

Time:09-12

I have read one article which says the following :

* Room will provide main-safety automatically if you use suspend functions, RxJava, or LiveData.

** Networking libraries such as Retrofit and Volley manage their own threads and do not require explicit main-safety in your code when used with Kotlin coroutines.

So I have two questions :

  1. If i will have one suspend function inside viewmodel and it's having long running task inside it and it does not use any dispatcher. So if I will call this function from activity/fragment, then will it work as simple function as we have not defined any dispatcher and will block the ui ?

  2. As stated above in the statements, for room/retrofit, should we use dispatcher explicitly(like IO in these cases) as they are taking care of background thread by themselves.

Googled it, did not get exact answer, so posting to get clarity.

CodePudding user response:

  1. Yes, the suspended function will run normally & will not block the UI unless you use a blocking coroutine like runBlocking or withContext that returns a value to the UI.
    A simple launch i.e. viewModelScope.launch would not block a thread.

  2. As per the docs they use a custom dispatcher to handle threading.
    From the code-lab docs:

Both Room and Retrofit make suspending functions main-safe.
It's safe to call these suspend funs from Dispatchers.Main, even though they fetch from the network and write to the database.

Both Room and Retrofit use a custom dispatcher and do not use Dispatchers.IO.
Room will run coroutines using the default query and transaction Executor that's configured.

Retrofit will create a new Call object under the hood, and call enqueue on it to send the request asynchronously.

CodePudding user response:

As my understand,

  1. When you call suspend function, you need to provide a coroutine scope. So, if you provide Dispatcher.Main or MainScope, it will block UI.

  2. Room/Retrofit has implicit coroutine scope. That means you don't need provide it for them. But when you call to Room/Retrofit, you will need to provide coroutine scope like [1]

  • Related