In a previous question (Android Kotlin Room Repository unable to retrieve row from within detail activity) I described my app that displays a list of walking routes (downloaded from the cloud) in a RecyclerView and, when a route is selected I want to display all details of the route - a simple Master-Detail app. I have most of it working fine using a Room database and a Repository. The database is correctly populated and the RecyclerView displays the list of routes. When a route is selected the routeID is correctly passed to an activity (TwalksRouteActivity.kt) where the route details are retrieved from the database and the details correctly displayed. Since I'm learning I also want to try and use best practice and I want to move the database calls out of the activity and into a ViewModel but I'm really struggling to get this working.
I have created a ViewModel (RouteViewModel) and wired this in to the activity (TwalksRouteActivity.kt). The ViewModel is correctly created and destroyed so now I should be able to move the data handling code from the activity to the ViewModel but that's where I'm stuck. In the activity I use lifecycleScope.launch (Dispatchers.Main) to handle the retrieval from the database but this structure doesn't work in the ViewModel so how can I replicate this functionality in the View Model?
The detail activity (TwalksRouteActivity.kt) is called from the RecylerView in (TwalksFragmen.kt) using an Intent and Bundle.
RouteViewModel.kt:
package com.example.android.twalks.viewmodels
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
class RouteViewModel(val savedStateHandle: SavedStateHandle) : ViewModel() {
//var bundle: Bundle? = intent.extras
//var routeID = bundle?.getInt("routeID")
var routeID = savedStateHandle.get<Int>("routeID")
init {
Log.i("CWM", "view model created")
Log.i("CWM", routeID.toString())
}
override fun onCleared() {
super.onCleared()
Log.i("CWM", "view model destroyed")
}
}