I have been learning and integrating MVP pattern
, and have few questions.
What i have understand from this diagram, is that
Activity will create instance of Presenter
, and pass its reference and model
object to the presenter
MainPresenter mainPresenter = new MainPresenter(this, new MainModel());
Next if presenter need to store or get any data from local preference or remotely, it will ask model.
And then model will ask repository for storing and retrieving data.
I followed few tutorials and this is how i implement the pattern.
Interface
public interface MainActivityMVP {
public interface Model{
}
public interface View{
boolean isPnTokenRegistered();
}
public interface Presenter{
}
}
Activity
MainPresenter mainPresenter = new MainPresenter(this, new MainModel());
mainPresenter.sendDataToServer();
Presenter
public void sendDataToServer() {
// Here i need to ask `model` to check
do network operation and save data in preference
}
Now the issue is i need context to access sharedPreference
, but i have not passed context
anywhere. I also don't want to use static context
. I want to know the proper way of passing context to MVP pattern.
Well, the best approach is to wrap your preferences class in a helper class and use Dagger to inject it anywhere you need, that way your presenter/model doesn't need to know about the Context. For example, I have an application module that provides a variaty of singletons, one of them is my Preferences Util class that deals with the Shared preferences.
@Provides
@Singleton
public PreferencesUtil providesPreferences(Application application) {
return new PreferencesUtil(application);
}
Now, anytime I want to use it I just @Inject it:
@Inject
PreferencesUtil prefs;
I think it's worth the learning curve as your MVP project will be more decoupled.
However, if you're willing to forget about the "Presenter doesn't know about Android context" rule you can simply add a getContext method to your view interface and get the Context from the view:
public interface MainActivityMVP {
public interface Model{
}
public interface View{
boolean isPnTokenRegistered();
Context getContext();
}
public interface Presenter{
}
}
And then:
public void sendDataToServer() {
Context context = view.getContext();
}
I've seen some people implement MVP like this, but my personal preference is to use Dagger.
You can also use the application conext, as suggested in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With