Is Task<T>.await() main-safe?

Viewed 155

I'm writing my first Kotlin app and am using firebase services for auth, db & storage. As it is not possible to make an atomic Firestore + Storage operation, I find myself in quit a callback-hell for a simple image upload (with error fallbacks and all). Thus - I decided to refactor my app to use coroutines. I found some examples (like here and here) but I noticed that the repository-level functions in those examples are not wrapped with withContext(Dispatchers.IO){ } like shown in android docs. Should they? I guess this is two questions in one:

  1. Should Firebase operations always be called with the IO dispatcher?
  2. Is kotlinx-coroutines-play-services's Task<T>.await() main-safe?

And a bonus question: I wrap all my Firebase calls in a proxy object for decoupling - is there a way to set all functions of an object (/class) to run with the same context, or do I have to wrap each function with withContext(Dispatchers.IO){ } separately?

Thanks a lot!

1 Answers
  1. Should Firebase operations always be called with the IO dispatcher?

All Firebase APIs are asynchronous and designed to be called safely from the main thread unless otherwise stated in the API documentation.

  1. Is kotlinx-coroutines-play-services's Task.await() main-safe?

Yes. As the API documentation states (emphasis mine):

Awaits for completion of the task without blocking a thread.

It's a suspend fun, and they do not block. However, they do not really make sense to call outside of a coroutine.

Related