Search code examples
androidmvpretrofit2

In an android MVP-structured app, what would be the "correct" way to pass a string resource as {path} to a Retrofit call?


In the Model layer, I've got a DataManager class that handles all Retrofit calls.

The retrofit methods need {path} parameters, because I store all REST endpoints as string resources in a separate xml file (for .gitignore purposes).

So if I don't want to pass a Context to neither the Model nor the Presenter layers (and do a context.getString), how do I get and pass these parameters?


Solution

  • the best way is to use dependency injection either using libraries like "Dagger 2" or by the help of dependency inversion.

    to do the first way you can refer to this link: (this way needs more code and time but the best practice - the most recommended to use in mvp architecture - learning is a bit complicated)

    http://www.vogella.com/tutorials/Dagger/article.html

    to do the second way do as below : (less code a little dirtier - use it if you dont want to use dagger)

    to provide this type of variables which needs some thing from android rather than pure java you can create a interface class and add some methods that provide your needs. code would be something like this:

    public interface Provider {
    public String providePath();
    }
    

    assuming your model and presenter is in a separate pure java module you must add this interface to the module in order to prevent circular dependency. then you implement this interface in your android class and send it to your presenter in each call.

    public class ProviderImpl implements Provider {
    
     private Context ctx;
     public ProviderImpl(final Context ctx) {
        this.ctx = ctx;
    }
    
    @Override
    public string providePath() {
        //provide the path from resources
    }
    }
    

    using this way you can add up every new need as a method to your Provider interface and use it in the presenter. you will have to get a Provider variable as argument in your presenters.

    I WOULD USE DAGGER MYSELF because that is a lot cleaner and the best practice.