Hey is it possible to get a single instance of a `...
# koin
m
Hey is it possible to get a single instance of a
viewModel { }
? Currently I have to manually create my
BarcodeDataReceiver
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
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).
Could you add a bit more context to your question? Where are you injecting these 2 ViewModels? Is it inside a Fragment?
To be honest your code as it is doesn't look bad.
p
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
shared ViewModel is a good idea to help reuse/wire with the same VM instance
m
@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.