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