9

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.

HelloCW
  • 843
  • 22
  • 125
  • 310

3 Answers3

12

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

Calin
  • 6,661
  • 7
  • 49
  • 80
6

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

Enselic
  • 4,434
  • 2
  • 30
  • 42
  • 1
    But that's confusing. Then "suspend" doesn't guarrantee main-safety. Only the method's implementation does. ???? – Juan José Melero Gómez Nov 27 '20 at 17:08
  • 1
    @JuanJoséMeleroGómez Correct, "suspend" by itself does not guarantee main-safety. A suspend fun can still block the UI thread if it is badly written. Roman talks about this explicitly here for example: https://elizarov.medium.com/blocking-threads-suspending-coroutines-d33e11bf4761 – Enselic Nov 27 '20 at 20:31
3

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.

Sarah Maher
  • 790
  • 1
  • 10
  • 21