android / codelab-android-hilt

Apache License 2.0
355 stars 188 forks source link

Fields in View injected twice #47

Open Aorlinn opened 2 years ago

Aorlinn commented 2 years ago

I have a view using field injection. I create the view inside another view by using a custom EntryPoint. I found out, that the fields inside the injected view are injected once during base class constructor, and once after creating the instance, but before the EntryPoint returns it. This leads to problems, as I am configuring the fields within the constructor and using it at a later state.

I try to give a simple code example:

@AndroidEntryPoint
public class InjectedView extends View
{
    @Inject
    protected Object mInstance;
    protected final Object mInstanceBackup;

    @Inject
    public InjectedView (@ActivityContext Context context)
    {
        super(context);
        mInstanceBackup = mInstance;
    }

    public void compare()
    {
        if(mInstance != mInstanceBackup)
        {
            throw new RuntimeExeption("Not the same");
        }
    }
}

@AndroidEntryPoint
public class Container extends ViewGroup
{
    public void method()
    {
        InjectedView view = EntryPointAccessors.fromView(this, InjectedViewCreator.class).create();
        view.compare();
    }
}

@EntryPoint
@InstallIn(ViewComponent.class)
public interface InjectedViewCreator
{
    InjectedView create();
}

Now when you call Container.method() it should throw an exception. I didn't test the example so I'm not sure if there is a specific configuration missing. But I used a field modification breakpoint on my mInstance field and saw that the field is modified within Hilt before the EntryPoint returns the injected view, so I'm sure it's not overwritten in my code.

I used Hilt version 2.43.2 and some random versions earlier, it's always the same problem.