icerockdev / moko-mvvm

Model-View-ViewModel architecture components for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
994 stars 95 forks source link

Can I integrate koin in compose multiplatform with koin ViewModel?? #262

Open shohrab-swl opened 6 months ago

shohrab-swl commented 6 months ago
val viewmodel: MyViewModel= getViewModel(
    key = MyViewModel::class.getFullName(),
    factory = viewModelFactory { MyViewModel(userDataRepository) }

Is it possible to koinInject??

NikhilBhutani commented 5 months ago

@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

NikhilBhutani commented 5 months ago

Hi @Alex009 , Can we please mark this as resolved ?

shohrab-swl commented 5 months ago

That code doesn't work when I create a new ViewModel.

NikhilBhutani commented 5 months ago

@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.

shohrab-swl commented 5 months ago

NewsAppDemoComposeMultiplatform.zip

fun presentationModule() = module { single { viewModelFactory { NewsHomeViewModel(get()) } } single { viewModelFactory { NewsDetailsViewModel(get()) } } }

object ViewModelsFac : KoinComponent { fun getNewsHomeViewModelFactory() = get<ViewModelFactory>() fun getNewsDetailsViewModelFactory() = get<ViewModelFactory>() }

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

NikhilBhutani commented 5 months ago

Thanks for sharing this @shohrab-swl , Can you please also add an issue in the original repo, I'll fix this.

NikhilBhutani commented 5 months ago

@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.

slikasgiedrius commented 2 months ago

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