From the course: Concurrent Programming with Android: Threads, Workers, and Kotlin Coroutines

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Run coroutines in a ViewModel class

Run coroutines in a ViewModel class

- [Narrator] Well architected Android apps frequently use the ViewModel component to manage network requests and access local files or databases. You can easily use coroutines from within a ViewModel by launching the coroutines from a special scope called ViewModelScope. First, I need a new dependency in the modules build file. I'll place it at the end of the list of dependencies and I'll use implementation and then the string androidx.lifecycle :lifecycle - viewmodel and then because I'm working in Kotlin -ktx. And I'll set the version to the most recent version as of the time of this recording. I'll sync that change and now I can use the ViewModelScope. I'll create a new Kotlin class. I'll name it MainViewModel. It's the ViewModel for the MainActivity. I'll set it to a class and create it. This class will be extended from the ViewModel class. Now within the ViewModel I want to expose the data that I'm…

Contents