Is there a way to use viewmodel defined in common code with Hilt? It needs a @HiltViewModel on class...
s
Is there a way to use viewmodel defined in common code with Hilt? It needs a @HiltViewModel on class and @inject on constructor.
j
Maybe using type alias like the parcelize approach with multi platform
👍 1
k
what would you expect to happen on non-Android platforms?
j
Nothing I guess. Another DI framework should be used or if it is jvm dagger without hilt
s
The idealistic way would be for hilt to also support providing viewmodels in modules... I think it is a pretty cool feature but I don't know where I can post a feature request.
I'm currently defining abstract viewmodels in common module and making concrete, annotated implementations in app module.
a
Hilt is android specific and probably might not working properly with common code. Koin could be an alternative to look into.
I've successfully used Koin in a KMM project injecting dependencies on both platforms using Koin
👌 1
s
@Manuel Vivo Would you please take a look at this? Is there another way that I'm missing? Pretty good use case for supporting module provided viewmodel I think. #FeatureRequeset 🙂
@Abhishek Dewan It works fine mostly.
m
Yeah! Unfortunately, Hilt doesn’t support KMP at the moment. There are some efforts going on to migrate Dagger to KSP first which will bring it closer to have some sort of KMP support. But that’d happen with Dagger, Hilt is Android-specific and doesn’t make sense to have it as a KMP library
👌 2
s
@Manuel Vivo But if we maybe could Provide Hilt viewmodels through Modules, we wouldn't need hilt inside KMP modules. We could just define the provider inside a module in app.
I of course don't know how hard that might be or what side effects that might have.
m
Well, I don’t think that’s possible at the moment. ViewModels were first shipped as an additional library. But as the
ViewModelComponent
was needed to solve certain problems, the team included ViewModels in core Hilt. I don’t think that’ll get reverted
s
I think it might have gotten a bit confusing because of Gradle Module and Dagger Module 🙂 I meant sth like this:
Copy code
// KMP shared module
class MainViewModel(...) : ViewModel() {  // ViewModel defined in Shared code. ViewModel is a TypeAlias for android ViewModel.
....
}

// App module
object ViewModelModule {
 @Provides
 @HiltViewModel  // This annotation can't be here currently. I mean this or sth similar.
 fun provideMainViewModel(...): MainViewModel {

 }
  ...
}
m
You could provide the VM using Dagger though
s
That is what I wanted to explore next 🙂 Just wanted to check with the community if there is a better way
m
I was actually thinking about sth like this: https://proandroiddev.com/connecting-the-dots-44d8fa79f14
s
Thanks thats great!