Search code examples
androiddependency-injectiondagger-2dagger

How to send data to my provides scope object in Dagger 2 every time


I want to send name to this method, which is in module class of dagger 2, I know It's Impossible nut I want to know is there any way to send data every time?

@Provides
Toast provideToast(String name){
    Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
    toast.setText(name);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
    return toast;
}

follow below is my component class

@Singleton
@Component(modules = {ApiModule.class,AppModule.class})
public interface ApiComponent {
   void inject(MainActivity activity);
}

Solution

  • Dagger provides consistent dependencies, and is unsuited for dynamic ones like message text. In the general case, if you need to mix dependencies from your graph with dynamic parameters, you can use AutoFactory. Here, you are describing the creation of a Toast object with no other dependencies, so there's no reason for Dagger to automate that mixing.

    Instead, you might want to create a ToastFactory or similar:

    public class Toaster {
      @Inject public Toaster() {}  // to make this class injectable
    
      public Toast provideToast(String name) {
        Toast toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
        toast.setText(name);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
        return toast;
      }
    }
    

    This would not allow you to inject Toast (because it needs a name supplied at runtime), but you could inject Toaster, and make all the Toasts you'd like.

    public class YourConsumer {
      private final Toaster toaster;
    
      @Inject public YourConsumer(Toaster toaster) { this.toaster = toaster; }
    
      public void onTrafficIncident() {
        toaster.provideToast("Encountered a jam");
      }
    }