-1

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);
}

1 Answers1

1

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");
  }
}
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • Do you know by any chance how to use AutoFactory and if it is applicable in this case? – EpicPandaForce Jun 23 '18 at 03:29
  • 1
    @EpicPandaForce I've written about AutoFactory before (e.g. [here](https://stackoverflow.com/a/29196676/1426891) and [here](https://stackoverflow.com/a/42261056/1426891)), but it is _not_ applicable here: AutoFactory generates a class that lets you mix instance-specific dependencies with dependencies from the graph, putting them into the same constructor call. That's all. This isn't the right solution for Toast (which uses a static factory method) or Toaster (which has no dependencies), but it could be the right solution for other injectable objects that have *some* immutable instance state. – Jeff Bowman Jun 25 '18 at 17:34