Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Playing with Hilt DI

Playing with Hilt DI

Hilt is one of the latest update from Jetpack. It brings a new way to implement the dependency injection over top of Dagger. It simplifies the process and the Dagger ritual to do the dependency injection with ease. It is still alpha version and worth to try!

Sidiq Permana

June 27, 2020
Tweet

More Decks by Sidiq Permana

Other Decks in Programming

Transcript

  1. Dependency Injection is one of inversion control (others : service

    locator, strategy pattern, factory pattern) technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service).
  2. Advantages Decoupling Dependency : Avoid hard dependency. Reusability : Reduce

    boilerplate and reinvent the wheel. Ease to Test : Replace the dependency with mock. Ease to Refactor : Improve code? No worry.
  3. Hilt is a dependency injection library for Android that reduces

    the boilerplate of doing manual dependency injection in your project. Build on top of Dagger library and simplified the ‘Dagger Ritual’ and implement DI with ease!
  4. Why Hilt? Build on Top Of Dagger. They can coexist.

    Simplify the Dagger Process. Set a standard of components and scopes to ease setup, readability, and code sharing between apps. Provide an easy way to provision different bindings to various build types, such as testing, debug, or release.
  5. Bindings It is a way to provide instances of the

    necessary dependencies from the corresponding component to perform the Field Injection. A binding contains the information necessary to provide instances of a type as a dependency. One way to provide binding information to Hilt is constructor injection with @Inject annotation.
  6. @AndroidEntryPoint Hilt can provide dependencies to other Android classes that

    have the @AndroidEntryPoint annotation. Current Android Classes supported : • Application (by using @HiltAndroidApp) • Activity (Only derivation of ComponentActivity such as AppCompatActivity) • Fragment (Not working in Retained Fragment and only androidx.Fragment) • View • Service • BroadcastReceiver
  7. Obtain dependency with @Inject Fields injected by Hilt cannot be

    private. Attempting to inject a private field with Hilt results in a compilation error.
  8. Conclusion • Hilt simplify the DI process compares to Dagger.

    It is even easier to you if you have any experience working with Dagger previously • It provides predefined components, scopes, bindings and qualifiers through annotations for Android Classes that helped us much! • Can be coexist with Dagger especially in DFM • It is still new and will be coming more features. So Give it try!