1

I am trying to use Dagger 2, and in a lot of examples I saw code like this:

MyComponent.java

@Singleton
@Component(modules = {SharedPrefModule.class})
public interface MyComponent {
    void inject(MainActivity activity);
}

SharedPrefModule.java

@Module
public class SharedPrefModule {
    private Context context;

    public SharedPrefModule(Context context) {
        this.context = context;
    }

    @Singleton
    @Provides
    public Context provideContext() {
        return context;
    }

    @Singleton
    @Provides
    public SharedPreferences provideSharedPreferences(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }
}

MainActivity.java

 @Inject
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        myComponent = DaggerMyComponent.builder().sharedPrefModule(new SharedPrefModule(this)).build();
        myComponent.inject(this);


    }

My doubt is if I really for inject do I need to put this?:

DaggerMyComponent.builder().sharedPrefModule(new SharedPrefModule(this)).build();

And if I want to inject in other class do I need to put another method in the MyComponent, for example, I want to inject SharedPreferences in MainViewModel Do I need to put void inject(MainViewModel mainViewModel); too?

If the answer is yes, what is really the advantage of this? what is the difference with only to apply a singleton pattern? or for inject use directly myComponent = new SharedPreferences(this);?

Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84
  • Definitely not the best way of doing things considering you are instantiating a "singleton" component every time your Activity is created, so none of those "singletons" in your "singleton scoped component" are actually singletons, because they die with the Activity lifecycle. As for ViewModels, they are created ONCE for until the Activity is *finished* (not destroyed, *finished*) but if you don't register it via ViewModelProviders then you won't get onCleared() callback. – EpicPandaForce Mar 03 '19 at 18:16

0 Answers0