Is this really the best form of inject something with dagger 2? or why dagger is a good option?

67 Views Asked by At

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

0

There are 0 best solutions below