What does main-safe in Kotlin Coroutines?

Viewed 1824

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 Answers

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

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.

Related