I’m having a scope crisis. I want to both instantiate a AndroidViewModel
from extras passed to onCreate
via Intent
and also have it available as a val
scoped to the entire class. Here is some code that I hope explains what I’m after. How can I achieve this?
fun onScan(
scan: String
) {
val kitID = scan
sendKitReserveRequest(
kitID = kitID,
shipmentID = viewModel.shipmentID, // <------- viewModel out of scope
onAlert = { title, message ->
dialogTitle.value = title // <------- dialogTitle is MutableState class scoped
dialogMessage.value = message // <------- dialogMessage is MutableState class scoped
showMessageDialog.value = true
},
onResponse = { response ->
viewModel.reserveKit( // <------- viewModel out of scope
kitID = kitID,
shipmentID = viewModel.shipmentID // <------- viewModel out of scope
)
},
showProgressDialog = showProgressDialog
)
}
/** Called when the activity is first created. */
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(intent.hasExtra(JSON.SHIPMENT_ID)) {
val viewModel by viewModels<ShipmentViewModel>(
factoryProducer = {
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return ShipmentViewModel(
application = application,
shipmentID = intent.getStringExtra(JSON.SHIPMENT_ID) ?: "0"
) as T
}
}
}
)
setContent {
ConceptualSystemsTheme {
Scaffold(
modifier = Modifier
.fillMaxSize()
) { scaffoldPadding ->
MainLayout(
scaffoldPadding,
viewModel
)
}
}
}
} else {
//shipmentID is required. eject from Activity if it is not available.
finish()
}
}
I would like for the viewModel instance to be an immutable val
available to the entire class, but the value comes from within onCreate
via the Intent
extras. Is it possible to achieve this without making a the ShipmentViewModel
a lateinit var
?