A practical guide to using Hilt with Kotlin

We invite future students on the course "Android Developer. Professional" to visit the open lesson on the topic "Writing a Gradle Plugin"







We also share the translation of a useful article.






An easy way to use dependency injection in Android apps

Hilt  is a new dependency injection library built on top of  Dagger . It allows you to use Dagger's capabilities in Android applications in a simplified way. This tutorial describes the basic functionality of the library and provides some code snippets to help you get started using Hilt in your projects.





Setting up Hilt

To set up Hilt in your application, first follow the instructions from the tutorial: Installing Gradle Build .





, Hilt,  Application  @HiltAndroidApp.



, Hilt .





, , , :





  1. , , .





  2. , .





: .





Hilt , Hilt .  .





Hilt.





  1.  @Inject







  2.  @Binds



     





  3.  @Provides



     





โฎ•   @Inject







 @Inject



, .





โฎ• 





Hilt .





Hilt  ยซยป, Hilt, , , โ€” , .





, . , -.





  Hilt,  @InstallIn



. .





1:  @Binds,





 OatMilk,  Milk,  @Binds



. , , OatMilk .  @Inject



.





2: -  @Provides







, .  โ€” -, .





,  ConnectivityManager, .





 Context  ,  @ApplicationContext



  @ActivityContext



.





, Hilt .













โฎ•





@Inject



, Hilt , .





โฎ•





,  @AndroidEntryPoint



( ), ,  @Inject



.





,  @Inject



,  . lateinit, ,  null



.





, , ,  Activity



. .





, ,    , ? ,    , , . , Android, Hilt.





    Hilt, Hilt , , .





โฎ• Android





  Android:





  • Activity





  • Fragment





  • View





  • Service





  • BroadcastReceiver





,  @AndroidEntryPoint



.





โฎ•





Android, , Dagger, Android, Hilt, Hilt . .





ViewModel

ViewModel โ€” : , , Android.  ViewModel



 @ViewModelInject



, Hilt ,  by viewModels()



. ,  @Inject



  .





, ViewModel



,  SavedStateHandle  ,  @Assisted



.





 @ViewModelInject



, . . : Hilt Jetpack.





  Hilt,  @InstallIn



(<>). . , @InstallIn



(ServiceComponent.class



) , , .





, , . โ€ฆ





. , ,  Milk,  OatMilk.  @ActivityScoped



ActivityComponent



.





, , Hilt  OatMilk  . ,  OatMilk   โ€”  onCreate()



   onDestroy()



 .





 milk,  moreMilk   OatMilk. ,  LatteActivity,  OatMilk.





, , , ,  OatMilk:





, . , @ActivityScoped



  , ,  ActivityComponent



.





:  Milk,  Fridge  LatteActivity, ,  onCreate()



   LatteActivity, โ€”  onDestroy()



. ,  Milk  ยซยป ,  onDestroy()



  . ,  @ActivityRetainedScope



.





, , , , , :  Hilt.





. , , - , , -.  dagger.Provider.





, . , ,  Provider<โ€ฆ>



, .





( Dagger  Guice) , . Hilt, , Dagger , , .





Hilt , , ,   -, .






"Android Developer. Professional"









" Gradle Plugin"






 OTUS   . . -    .   - :












All Articles