moko-mvvm
moko-mvvm copied to clipboard
Can I integrate koin in compose multiplatform with koin ViewModel??
val viewmodel: MyViewModel= getViewModel(
key = MyViewModel::class.getFullName(),
factory = viewModelFactory { MyViewModel(userDataRepository) }
Is it possible to koinInject??
@shohrab-swl Yes, you can. Inject ViewModelFactory and access it an Koin Object.
And in your composable use your above code snippet and instead of declaring
viewModelFactory { MyViewModel(userDataRepository) }
Instead get your koin generated viewmodelfactory object.
I have created an example here - https://github.com/NikhilBhutani/ComposeMultiplatformNewsAppDemo/blob/main/shared/src/commonMain/kotlin/com/niko/kmm/newsappdemocomposemultiplatform/di/PresentationModule.kt
Hi @Alex009 , Can we please mark this as resolved ?
That code doesn't work when I create a new ViewModel.
@shohrab-swl Can you please share your repo so that I can check whats not working for you? Or maybe you can clone my repo above and add api key to inspect how it's working. ? Let me know, glad to help out in any way.
NewsAppDemoComposeMultiplatform.zip
fun presentationModule() = module { single { viewModelFactory { NewsHomeViewModel(get()) } } single { viewModelFactory { NewsDetailsViewModel(get()) } } }
object ViewModelsFac : KoinComponent { fun getNewsHomeViewModelFactory() = get<ViewModelFactory<NewsHomeViewModel>>() fun getNewsDetailsViewModelFactory() = get<ViewModelFactory<NewsDetailsViewModel>>() }
I just changed a few lines.
and i get this error
java.lang.ClassCastException: com.niko.kmm.newsappdemocomposemultiplatform.presentation.details.NewsDetailsViewModel cannot be cast to com.niko.kmm.newsappdemocomposemultiplatform.presentation.NewsHomeViewModel
Thanks for sharing this @shohrab-swl , Can you please also add an issue in the original repo, I'll fix this.
@shohrab-swl You can do this.
object ViewModelsFac : KoinComponent { fun getNewsHomeViewModelFactory() = viewModelFactory { NewsHomeViewModel(get()) } fun getNewsDetailViewModelFactory() = viewModelFactory { NewsDetailsViewModel() } }
and access it with getViewModel in your composable.
It's hard to understand the concept, but I made it work based on this conversation. I suggest you to add this case to the instructions