7 steps to implement Dagger 2 in Android

Modify MainActivity class:We need to implement HasSupportFragmentInjector in our Activity if we want to inject the ViewModelFactory class in our Fragment..And also, move all our RecyclerView.Adapter and ViewModel implementation to the Fragment class.MainActivity.javaMainActivity.kt4..Add MovieFragment class:Lastly, we need to create our Fragment class..We inject the ViewModelFactory into the Fragment and initialise the viewModel..The remaining implementation is the same.MovieListFragment.javaMovieListFragment.kt5..Add FragmentModule class to AppComponent:@Component( modules = [ ApiModule::class, DbModule::class, ViewModelModule::class, ActivityModule::class, FragmentModule::class, AndroidSupportInjectionModule::class])You can checkout this commit to find out the differences between injecting into Activity and injecting into fragment for Java and this commit for Kotlin.And that’s it!.????..I know it feels overwhelming and kinda a lot of work but in the end it’s worth it, I think.You can find the GitHub link for this sample implementation here:The master branch — contains Dagger implementation in Activity in Java.The kotlin_support branch — contains Dagger implementation in Activity in Kotlin.Fragment injection implementation can be found under:inject_into_fragment_dagger_java — contains Dagger implementation in Fragment in Java.inject_into_fragment_kotlin — contains Dagger implementation in Fragment in Kotlin.For those of you interested in the whole app implementation, (and not just the simplified version we implemented here), you can checkout the Github project from here.The master branch — code in JavaThe kotlin_support branch — code in KotlinI hope you enjoyed this article and found it useful, if so please hit the Clap button..Let me know your thoughts in the comments section.Happy coding!.Thanks for reading!. More details

Leave a Reply