Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it necessary to use IO dispatcher for Firestore calls in Kotlin Coroutines?

I’m using Firebase Firestore to store some data on the cloud, and I realized that I’m using the Main (UI) dispatcher to call suspend and non-suspend functions. Can this cause me to freeze my UI?


There is a call to Firestore:

  suspend fun saveTask(task: Task) {
    tasksCollection
      .document(task.id)
      .set(task.toTaskDataMap())
      .await() // This is the suspending function.
  }

Call to the repository from the view model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  fun onSaveTaskClicked() = viewModelScope.launch(saveTaskExceptionHandler) {
    val task: Task = /* Building the task class */

    /* Validating the task data */

    taskRepository.saveTask(task)
    
    /* Navigation logic after task is successfully saved */
  }

Should I call the saveTask() function with the IO dispatcher or not?

>Solution :

Absolutely not. The point of a suspend function (like await()) is that it doesn’t block. Dispatchers.IO is for calling blocking IO functions.

It is possible to write a suspend function that calls blocking code without using an appropriate dispatcher. This would be a blocking suspend function, but it breaks convention and is incorrect. You can trust libraries from reputable sources like Google and Square won’t expose incorrectly blocking suspend functions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading