Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel Singleton With Koin

One of the objects that I am trying to inject captures a references in a lambda. That lambda is used as a callback to update my viewModel. How can I use koin to inject that object?

Working code that does not use dependency injection for:

private val viewModel: MyViewModel by viewModel()
private val barcodeDataReceiver =
    BarcodeDataReceiver {
        viewModel.addItem(it)
    }

I would ideally like to create my BarcodeDataReceiver with koin, but when I use get<MyViewModel>() I am getting a new instance of MyViewModel. I know that koin's viewModel { } is a factory, but is there any way to get a singleton?

I tried wrapping viewModel { } with single { } but that doesn't work.

like image 495
Miguel Vila Ojito Avatar asked May 09 '26 13:05

Miguel Vila Ojito


1 Answers

I'm not sure if you've already found an answer to your question, but since there's no answer yet, I'll share the solution I found:

With Koin, a ViewModel can be created as a Singleton just like any other object by using the single declaration, whether it's a full

single{SingletonViewModel(get())}, where with get() you receive ViewModel constructor parameter

or shorthand declaration

singleOf(::SingletonViewModel)

And injected into the code using koinInject<SingletonViewModel>().

I tested this approach in a KMM app, and I indeed get the same data model. I believe this would also apply to a pure Android app.

like image 173
SmirnovDV Avatar answered May 11 '26 01:05

SmirnovDV