Miguel Vila Ojito
Miguel Vila Ojito

Reputation: 31

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.

Upvotes: 3

Views: 500

Answers (1)

SmirnovDV
SmirnovDV

Reputation: 21

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.

Upvotes: 1

Related Questions