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 :
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 ?
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:
Yes, the suspended function will run normally & will not block the UI unless you use a blocking coroutine like
runBlocking
orwithContext
that returns a value to the UI.
A simplelaunch
i.e.viewModelScope.launch
would not block a thread.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,
When you call
suspend
function, you need to provide a coroutine scope. So, if you provideDispatcher.Main
orMainScope
, it will block UI.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]