Hello, I’m having trouble injecting the same insta...
# koin
m
Hello, I’m having trouble injecting the same instance of a viewmodel. Module:
Copy code
viewModel(named("CartViewModel")) { CartViewModel(get(), get()) }
My activity and fragment return same instance by using viewmodel delegates But I have a
Presentation
class which represents a secondary display, I want to observe some VM state changes on this screen. Since it is a
Presentation
which basically just extends
Dialog
I have no lifecycle components to leverage and can not use the typical injection patterns that are so easy with Activity/Fragments. Presentation Class
Copy code
companion object {
        var VM_STORE: ViewModelStore? = null
    }

    override val viewModelStore: ViewModelStore
        get() {
            if (VM_STORE == null) {
                VM_STORE = ViewModelStore()
            }
            return VM_STORE!!
        }


    // TODO - This is not injecting the single instance of CartViewModel...
    private val cartViewModel = getViewModel(
        owner = this,
        clazz = CartViewModel::class.java,
        qualifier = named("CartViewModel")
    )
Any thoughts on how I can retrieve the single VM instance which my activity/fragment are already using?
a
The interest of VM is to be bound to UI lifecycle. What is the interest her to try to mimic Android lifecycle to be able to use ViewModel? Perhaps you could just inject a factory instance
m
The reason is because
CartViewModel
exposes a flow that is observed by the primary screen(activity/fragment). The data exposed in that flow also needs to be displayed on the secondary display. I tried injecting a factory instance of
CartViewModel
in the Presentation class but a new flow is created since its a new VM instance and the flow from the VM instance which the fragment is using is never observed. I have an application scoped VM that handles changing the secondary display, it seems more appropriate to pass this job onto that VM.
a
if all the screen that needs instance lies under a single activity might be you can try something as activityScoped viewmodel , but not sure if koin supports it
or by default each new destination will have a new viewmodel
a
You can host dependency on a ViewModelScope if you want to hold a component over an Activitiyyt lifetime