In compose (Android), I have multiple instances of...
# koin
m
In compose (Android), I have multiple instances of a ViewModel each with a unique key. This is working fine. However, when I try to retrieve all the instances with
Koin.getAll()
always a single new instance is returned (and none of the existing instances). Is this a bug, or is there another way to do this?
a
did you tried with latest 3.5.5 version? fixed since 3.5.4
m
I just tried, and same issue
a
argh, didn't read fully. `Koin.getAll()`will not bind/use ViewModel factory. ViewModel are factory instances, wired on Android lifecycle through ViewModel API. What is your case, gathering all VM instances?
m
Yeah, I have a bunch of dialogs and each one has its own viewmodel (each one holds the state of each dialog). At some point I want to clear all dialogs. So I want to iterate over all dialog view models and set the dialog state to null on each.
Each dialog view model is retrieved by a key (essentially the index). The first dialog is at index 0 and then if it spawns another dialog then that will be index 1 and so on
a
ViewModel instances are not kept in Koin. You would need to address ViewModelProvider low level factory to address all of them 🤔
m
I’m trying to figure out how to resolve the viewmodels from the
ViewModelStore
(since composables have access to
LocalViewModelStoreOwner
), but unfortunately the methods I want to use are restricted to the library group. Any tips?
a
take a look at
resolveViewModel
from Koin
It's also used from Compose side
m
Thanks Arnaud. This seems to do the trick:
Copy code
fun ViewModelStore.resolveViewModel(key: String): DialogViewModel {
    val provider = ViewModelProvider(this, object : ViewModelProvider.Factory { })
    return provider[key, DialogViewModel::class.java]
}
Note: I’m assuming it’s okay to pass this empty instance of
Factory
(which would throw an exception if one of the create methods is called). This avoids the need for
KoinScope
. Update: oh actually, this only works for my use case, since I can detect when a view model is the last instance and so never call with a non-existent key).
Side note: I noticed that the key is used in a map not restricted to a particular VM class, so I guess the key should have, for example, fully qualified classname prefix to ensure uniqueness.
a
yes key is unique. Qualifier is postfixed with class full qualifier to help in the same way
👍 1
m
I actually ended up changing to a single view model which holds a map of the dialog states by key.
👍 1
408 Views