codelab-android-hilt icon indicating copy to clipboard operation
codelab-android-hilt copied to clipboard

Fields in View injected twice

Open Aorlinn opened this issue 3 years ago • 0 comments

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.

Aorlinn avatar Sep 14 '22 22:09 Aorlinn