google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.45k stars 2.02k forks source link

Allow Hilt injection first without BaseFragment or BaseActivity #2440

Open takahirom opened 3 years ago

takahirom commented 3 years ago

Thanks for the great tools! I'm not really in trouble, so it's okay for reference only.

To inject first, you need to prepare an inject method with BaseFragment etc.

https://github.com/google/dagger/releases/tag/dagger-2.33

abstract class BaseActivity extends FragmentActivity {
  @Override
   protected void onCreate(Bundle savedInstanceState) {
    inject(); // <- This will force early injection.
    foo.doSomething();
    super.onCreate();    
  }

  // An inject method to be overridden by the Hilt generated class.
  protected void inject() {
    throw new UnsupportedOperationException();
  }
}

For example, how about providing an interface like HiltInjectable?

Generated code

public abstract class Hilt_PlayerFragment extends Fragment implements GeneratedComponentManagerHolder,
   **HiltInjectable** {
....
   @Override
   protected void inject() {
...
   }

Library code

interface HiltInjectable{
    fun inject()
    companion object {
        fun inject(any: Any){
            (any as HiltInjectable).inject()
        }
    }
}

App code

@AndroidEntryPoint
class PlayerFragment : Fragment(R.layout.fragmenet_player) {
    @Inject
    lateinit var custom: FragmentModule.Custom

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        HiltInjectable.inject(this)
        println("custom:" + custom)
        super.onViewCreated(view, savedInstanceState)
    }
}
Chang-Eric commented 3 years ago

Note that this is only a problem if using the bytecode transform, so a workaround is that you can extend the generated base class manually (see: https://dagger.dev/hilt/gradle-setup.html#why-use-the-plugin)