Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context to repository in MVP pattern

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.

enter image description here

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.

like image 857
Taha Kirmani Avatar asked May 03 '18 12:05

Taha Kirmani


1 Answers

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.

like image 174
Levi Moreira Avatar answered Oct 05 '22 23:10

Levi Moreira