Now create a ViewModel class named MainViewModel.kt.
Here is the MainViewModel.kt class:
open class MainViewModel(application: Application) : AndroidViewModel(application) {
private val mRepository: UsersRepository
private val mAllUsers: LiveData<List<Users>>
private var parentJob = Job()
private val coroutineContext: CoroutineContext
get() = parentJob + Dispatchers.Main
private val scope = CoroutineScope(coroutineContext)
init {
val userDao = UsersRoomDatabase.getDatabase(application, scope).userDAO()
mRepository = UsersRepository(userDao)
mAllUsers = mRepository.mAllUsers
}
fun getAllUsers(): LiveData<List<Users>>{
return mAllUsers
}
fun insert(users: Users) = scope.launch(Dispatchers.IO){
mRepository.insert(users)
}
override fun onCleared() {
super.onCleared()
parentJob.cancel()
}
}
This class gets the Application as a parameter and extends the AndroidViewModel.
Initialize a private variable of WordRepository and a LiveData, which will cache the list of the users.
In the init block, add a UserDAO reference from the UsersRoomDatabase. Initialize the mAllUsers with the mRepository.mAllUsers.