viewModelScope.launch(Dispatchers.IO) purpose
Asked Answered
P

1

13

In the codeLabs tutorial (Android - Kotlin - Room with a View), they have used "viewModelScope.launch(Dispatchers.IO)" to call insert method. what exactly it is and why is it used for. Refer the link,

https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#8

fun insert(word: Word) = viewModelScope.launch(Dispatchers.IO) {
    repository.insert(word)
}
Prunelle answered 3/5, 2019 at 17:23 Comment(2)
medium.com/androiddevelopers/… medium.com/androiddevelopers/…Electromotive
The real question is, "why aren't they using the GlobalScope for this". Who wants to cancel an insertion to the DB when you navigate back from a screen??Interoffice
E
17

viewModelScope is a CoroutineScope which is tied to your ViewModel. it means that when ViewModel has cleared coroutines inside that scope are canceled too.

Dispatchers.IO means that suspend fun repository.insert(word) will run in IO thread which is managed by kotlin.

there are different Dispachres. Dispatchers.IO is used for IO works like database or remote server. Dispatchers.Default is used for tasks that has high CPU usage. Dispatchers.Main is used for tasks that need to update UI.

Exportation answered 5/8, 2020 at 9:47 Comment(2)
So should all respository.* suspend funs be executed with Dispatcher.IO ?Bevin
@Bevin yes. all repository suspend functions that hit the database should be executed with Dispatchers.IOExportation

© 2022 - 2024 — McMap. All rights reserved.