moko-mvvm icon indicating copy to clipboard operation
moko-mvvm copied to clipboard

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

Open shohrab-swl opened this issue 1 year ago • 8 comments

val viewmodel: MyViewModel= getViewModel(
    key = MyViewModel::class.getFullName(),
    factory = viewModelFactory { MyViewModel(userDataRepository) }

Is it possible to koinInject??

shohrab-swl avatar Dec 18 '23 12:12 shohrab-swl

@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 avatar Jan 08 '24 17:01 NikhilBhutani

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

NikhilBhutani avatar Jan 14 '24 19:01 NikhilBhutani

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

shohrab-swl avatar Jan 15 '24 06:01 shohrab-swl

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

NikhilBhutani avatar Jan 15 '24 07:01 NikhilBhutani

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

shohrab-swl avatar Jan 15 '24 08:01 shohrab-swl

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

NikhilBhutani avatar Jan 16 '24 05:01 NikhilBhutani

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

NikhilBhutani avatar Jan 17 '24 19:01 NikhilBhutani

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

slikasgiedrius avatar Apr 23 '24 18:04 slikasgiedrius