@ViewModelInject
Simply paste this annotation into the ViewModel and you can automatically inject it. At this time, the ViewModel constructor can take advantage of all the dependency available through the @Activity RetainedComponent
scope, or can selectively take advantage of the @Assisted
annotation to use the SavedStateHandle
.
Now, let’s look through the code.
🥇 Koin
The following code shows the implementation using the existing Koin.
DataSourceModule
— Provides a data source that serves to import the required data after receiving an API service injection.
NetWorkModule
— Sets Retrofit and OkHttp and provides services.
ViewModelModule
— Receives the intent argument parameter and provides the viewModel via injection of the repository.
And that’s how Activity used it to hand over the required argument in ViewModel.
In the application class, the module was inserted into the startKoin
function and used.
🗡 Dagger-Hilt
Now let’s use Dagger-Hilt to change the code created using the Koin. First, let’s start with a build.gradle
file. Create the dependency in the project level build.gradle
file as follows
It also writes the module-level build.gradle
file as follows
From now on, Write code the modules in the same way. Please check it while comparing it with the code created by the Koin above.
DataSourceModule
NetworkModule
RepositoryModule
⚠️ Unlike the Koin, Dagger-Hilt does not require you to create a separate module for the ViewModel, and you can inject dependencies by attaching the ViewModelInject
annotation to the ViewModel.
Assisted
annotation allows you to inject a SavedStateHandle
to easily load and use the required intent argument.
And this is how you use it in Activity.
Finally, for the Application class, you just have to add an annotation called HiltAndroidApp
.
Conclusion
So I tried to use DI library with Koin and Dagger-Hilt easily, but in my opinion, the Dagger-Hilt is still in alpha stage, but I didn’t think there were many references and it was too early to use it at production level. Nevertheless, the official version will be released soon, so I think you good learn beforehand.
The full code can be found here. If this posting was helped, please give a star at GitHub.
hongbeomi/HarryPotter |
![]() |
Thank you for reading it! 🙌