kluck
12/06/2023, 4:11 PM@Composable
inline fun <reified T : Container<S, I, A>, S : MVIState, I : MVIIntent, A : MVIAction> storeViewModel(
viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
},
key: String? = null,
extras: CreationExtras = defaultExtras(viewModelStoreOwner),
scope: Scope = getKoinScope(),
noinline parameters: ParametersDefinition? = null,
): StoreViewModel<S, I, A> = getViewModel(qualifier<T>(), viewModelStoreOwner, key, extras, scope, parameters) // -> This is a koin method
What I came up with:
@Composable
fun <S : MVIState, I : MVIIntent, A : MVIAction> storeViewModel(
viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
},
tag: Any? = null,
): StoreViewModel<S, I, A> = with(localDI()) {
getViewModel(viewModelStoreOwner = viewModelStoreOwner, tag = tag, di = this)
}
@Composable
inline fun <reified T : ViewModel> getViewModel(
viewModelStoreOwner: ViewModelStoreOwner,
tag: Any?,
di: DIAware,
): T = resolveViewModel(T::class, viewModelStoreOwner, tag, di)
inline fun <reified T : ViewModel> resolveViewModel(
vmClass: KClass<T>,
viewModelStoreOwner: ViewModelStoreOwner,
tag: Any?,
di: DIAware,
): T {
val factory = di.viewModelFactory(tag)
val provider = ViewModelProvider(
store = viewModelStoreOwner.viewModelStore,
factory = factory,
defaultCreationExtras = defaultExtras(viewModelStoreOwner),
)
return provider[vmClass.java]
}
fun DIAware.viewModelFactory(tag: Any?): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T =
di.direct.Instance(type = erased(modelClass), tag = tag)
}
It kind-of works, as I manage to retrieve my first store view model (val store = storeViewModel<MainState, MainIntent, MainAction>(tag = MAIN_STORE_TAG)
). But as soon as I try injecting a second one, it retrieves the first one… I use tags to distinguish the two, but I guess there is some erasing stuff that I don't get correctly… Any idea what I could change in my code?
Thanks!kluck
12/06/2023, 4:26 PMprovider[tag, vmClass.java]
instead of provider[vmClass.java]
. Not sure if it's the best solution though…romainbsl
12/07/2023, 11:04 AMkluck
12/11/2023, 7:45 AMprovider[tag, vmClass.java]
, thanks!romainbsl
12/11/2023, 7:49 AMkluck
12/11/2023, 8:08 AMVaizin Nikita
01/06/2025, 9:53 AM