How to access context in repository [MVVM]

Josip Domazet :

I am developing an Android application by using the MVVM architecture. My problem is that my repository (that is responsible for fetching JSON from the web) needs access to a context.

I've read several suggestions on stackoverflow. So far the most reasonable options I've gathered are the following:

  • Use Dagger 2 to somehow inject the context

  • Let my ViewModel extend from AndroidViewModel to get the application context and pass that to the repo

As of right now I have one ViewModel and one Repo

RoomFragmentViewModel.java:

public class MyViewModel extends ViewModel {
    private MutableLiveData<List<JSONObject>> rooms;
    private Repository repository;

    public void init(){
        if(rooms != null){
            return;
        }
        repository = repository.getInstance();
        rooms = repository.getRooms();
    }

Repository.java:

public class Repository {

    private static Repository instance;
    private ArrayList<JSONObject> actualRooms = new ArrayList<>();


    public static Repository getInstance() {
        if (instance == null) {
            instance = new Repository();
        }
        return instance;
    }


    public MutableLiveData<List<JSONObject>> getRooms() {
        ...
    }

    private void setRooms() {
        ...
        // Here I am fetching data from my server, but in order to to do so I require a context

        String url = "http://10.0.0.5:8000/api";

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.GET, null, new Response.Listener<JSONObject>() {...

        // Context needs to be provided right here:
        MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);

    }
}

Due to contradictory statements on the Internet I am unsure how I should resolve this problem. If your answer makes use of dagger could you be so nice to provide an explanation with code since I am completely new to dagger. Thank you in advance.

Josip Domazet :

I ended up injecting the context via dagger. However, from my point of view making your ViewModel extend from AndroidViewModel is also an valid option and definitely the easier one. If I were developing an simple and small application I would probably recommend just extending from AndroidViewModel to avoid unnecessary boilerplate code from dagger.

I followed the dagger series from codingwithmith in order to implement my own solution. So his channel might be useful for future readers: https://www.youtube.com/channel/UCoNZZLhPuuRteu02rh7bzsw/featured

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141465&siteId=1