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