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 contributes to structured concurrency by adding an extension property to the ViewModel class that automatically cancels its child coroutines when the ViewModel is destroyed.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With