2
votes

I'm learning Coroutines of Kotlin. The Text A is from https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#8

What does main-safe in Kotlin Coroutines?

Does it mean the system will run them in background thread automatically when it need ?

Does it mean I will never use the code such as withContext(Dispatchers.IO) in both Room and Retrofit operation ?

Text A

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.

3

3 Answers

3
votes

What does main-safe [mean for] Kotlin Coroutines?

You literally quote the answer yourself:

It's safe to call these suspend funs from Dispatchers.Main, even though they fetch from the network and write to the database.

And the answer to

Does it mean I will never use the code such as withContext(Dispatchers.IO) in both Room and Retrofit operation ?

is: Correct (assuming you configure them properly, e.g. use suspend modifier in Retrofit fun definitions).

2
votes

For me as an android developer this simple definition made perfect sens

We consider a function main-safe when it doesn't block UI updates on the main thread.

Found it here https://developer.android.com/kotlin/coroutines

0
votes

Please check this answer for the exact reason why the API calls works with retrofit without changing the dispatcher to IO, referencing https://stackoverflow.com/a/61216333/4354001 :

It works because Retrofit's suspend implementation delegates to Call.enqueue. This means it already executes on its own background executor by default instead of using the caller's Dispatcher.