Usage of the ViewModelScope

Based on my last post about easy implementation on Kotlin Coroutines, we were also introduced with the CoroutineContext .That was not too hard to understand, but I think there is a lot of code inside a ViewModel . First you needed a Job() , than you needed a CoroutineScope and in the instantiation you needed to specify one default Dispatcher . After that, you needed to keep track of the CoroutineContext corresponding to the ViewModel/Activity/Fragment lifecycle.

Note: If you are not using a ViewModel skip this post entirely.

Current code:

This is not very long code. However, think of every ViewModel you will be having inside your project. So, you will need some refactoring,or not.
This approach looks nice but has some unnecessary code.

Luckily there is another way of dealing with the CoroutineContext , thanks to Google. There is a lifecycle dependency which provides and keeps track of the CoroutineContext without declaring the Job() , the CoroutineScope and canceling on the onCleared() method.

Introducing the ViewModelScope:

Add this in your build.gradle(module app):

Now check how the ViewModel looks:

Of course, the Dispatchers need to be specified. Another thing we must be careful is that when we fire a coroutine tracked by the viewModelScope and we do not specify the thread it is going to run on the main thread. That’s because the viewModelScope runs on the Dispatchers.Main by default.

Happy ViewModelScoping.