Skip to content
Advertisement

Passing runtime parameter to constructor in Hilt

In Dagger, we can pass the runtime parameter through component.builder. But how to achieve that in hilt where the Component is Built in?

public class ProgressData {
private int percent;
@Inject
public ProgressData(int percent) {
    this.percent = percent;
}
public int getPercent() {
    return percent;
}
public void setPercent(int percent) {
    this.percent = percent;
}

How to inject an object of ProgressData in the main activity while percent data is set in runtime?

Advertisement

Answer

I found the answer. First Annotate the constructor with @AssistedInject. then we have to annotate percent as @Assisted.

public class ProgressData {
    private int percent;
    @AssistedInject
    public ProgressData(@Assisted int percent) {
        this.percent = percent;
    }

    
    public int getPercent() {
        return percent;
    }

    public void setPercent(int percent) {
        this.percent = percent;
    }
}

Then to provide value for percent we have to create a factory interface where we can pass all dependent variables. we have to annotate it with @AssistedFactory. Hilt will implement it internally.

@AssistedFactory
public interface ProgressDataFactory{
    ProgressData create(int percent);
}

Then from Activity or where we want we have to Inject the ProgressDataFactory .then we can call create function.

@Inject ProgressDataFactory progressDataFactory;
progressData=progressDataFactory.create(10);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement