Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewModelScope.launch(Dispatchers.IO) purpose

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)
}
like image 211
Goutham Avatar asked May 03 '19 17:05

Goutham


People also ask

What does viewModelScope launch do?

viewModelScope contributes to structured concurrency by adding an extension property to the ViewModel class that automatically cancels its child coroutines when the ViewModel is destroyed.

What is the viewModelScope?

A ViewModelScope is defined for each ViewModel in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared. Coroutines are useful here for when you have work that needs to be done only if the ViewModel is active.

What is dispatcher IO Android?

Dispatchers.IO is designed to be used when we block threads with I/O operations, for instance when we read/write files, use Android shared preferences, or call blocking functions. The code below takes around 1 second because Dispatchers.IO allows more than 50 active threads at the same time.

What is dispatcher IO Kotlin?

Kotlin coroutines use dispatchers to determine which threads are used for coroutine execution. To run code outside of the main thread, you can tell Kotlin coroutines to perform work on either the Default or IO dispatcher. In Kotlin, all coroutines must run in a dispatcher, even when they're running on the main thread.


1 Answers

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.

like image 169
Ehsan souri Avatar answered Sep 21 '22 09:09

Ehsan souri