object manually because I need to capture two of my viewModels in a lambda that's used for updating the UI.
Copy code
private val storeItemViewModel: StoreItemViewModel by viewModel()
private val scanningViewModel: ScanningViewModel by viewModel()
private val bScanner: BarcodeScanner by inject()
private val barcodeDataReceiver =
BarcodeDataReceiver {
storeItemViewModel.addItem(
it,
LoadingResource(scanningViewModel::toggle)
)
}
Ideally I would like to simply inject my
BarcodeDataReceiver
, but with
viewModel {}
being a factory I can't get the single instance that I need.
c
curioustechizen
01/11/2024, 6:01 AM
viewModel
is by definition a
factory
(but tied to a specific scope). If you call
by viewModel()
multiple times in the same scope, you'll get the same instance back.
(Here "scope" depends on how you're using ViewModels, it differs for example if you're injecting it into a Fragment versus if you're injecting it into an AndroidX navigation composable destination).
curioustechizen
01/11/2024, 6:02 AM
Could you add a bit more context to your question? Where are you injecting these 2 ViewModels? Is it inside a Fragment?
curioustechizen
01/11/2024, 6:04 AM
To be honest your code as it is doesn't look bad.
p
Pedro Alberto
01/12/2024, 11:54 AM
for that could it be the activityViewModel better since it seems you want to have a SharedViewModel @arnaud.giuliani@curioustechizen what do you think ?
a
arnaud.giuliani
01/12/2024, 5:58 PM
shared ViewModel is a good idea to help reuse/wire with the same VM instance
m
miggs597
01/22/2024, 9:42 PM
@curioustechizen right now the
barcodeDataReceiver
is created in my android application's main activity. But I was hoping to create it in my koin app module.