在 Fragment 中使用 ViewModel 和 RecyclerView 时,何时何地是发出 Web 请求的正确位置

When and where is the right place to make a web request when using a ViewModel and RecyclerView inside a Fragment

在片段的一侧,我使用 ViewModel 将数据加载到 RecyclerView。我的问题是发出网络请求的正确位置在哪里。现在我正在 ViewModel class 中的 populateList 中执行此操作,但它似乎没有正确加载到视图中所以我想知道是否我应该在其他地方执行此操作?

ViewModel

public class twoViewModel  extends ViewModel {

    MutableLiveData<ArrayList<User>> userLiveData;
    ArrayList<User> userArrayList = new ArrayList<>();

    public twoViewModel() {

        userLiveData = new MutableLiveData<>();
        // call your Rest API in init method
        init();

    }

    public MutableLiveData<ArrayList<User>> getUserMutableLiveData() {
        if(userLiveData==null)
            userLiveData = new MutableLiveData<>();
        return userLiveData;
    }


    public void init(){
        populateList();
        getUserMutableLiveData().setValue(userArrayList);
    }

    public void populateList() {
              // Is this the right place?

        System.out.println("********* populateList *********");

   String url = "https://eliyah.com/wp-json/wp/v2/archive?page=1";

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
                (com.android.volley.Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {

                            JSONObject jObj = response.getJSONObject(0);
                            // Get title
                            String title = jObj.getJSONObject("title").getString("rendered");
                            String[] desc = {"06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)"};

                            User user = new User();
                            try {
                                user.setTitle(title);
                                user.setDescription(desc[0]);
                               

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            userArrayList.add(user);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                      // TODO figure out how to return userArrayList
                      
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error

                    }
                });
        MySingleton.getInstance(GlobleContextreRerence.instance.getApplicationContext()).addToRequestQueue(jsonArrayRequest);

编辑

在视图模型中:


 public void populateList() {
        System.out.println("********* populateList *********");


        WebRequest b = new WebRequest(userArrayList);
        userArrayList = b.getx();
}

接口:


public interface VolleyCallBack {
    ArrayList<User> onSuccess(ArrayList<User> result);
}

存储库:

public class WebRequest implements VolleyCallBack {
    ArrayList<User> userArrayList;


    public WebRequest(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
    }


    @Override
    public ArrayList<User> onSuccess(ArrayList<User> userArrayList) {
        this.userArrayList = userArrayList;
        return userArrayList;
    }


    public ArrayList<User> fromAPI(final VolleyCallBack callBack) {

        String url = "https://eliyah.com/wp-json/wp/v2/archive?page=1";

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
                (com.android.volley.Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {

                            JSONObject jObj = response.getJSONObject(0);
                            // Get title
                            String title = jObj.getJSONObject("title").getString("rendered");
                          

                            String[] desc2 = {"06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)", "06/05/21 (03/24)"};


                            User user = new User();
                            try {
                                user.setTitle(title);
                                user.setDescription(desc2[0]);
                           

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            userArrayList.add(user);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        callBack.onSuccess(userArrayList);
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO: Handle error

                    }
                });


        MySingleton.getInstance(GlobleContextreRerence.instance.getApplicationContext()).addToRequestQueue(jsonArrayRequest);


        return userArrayList;

    }


    public ArrayList<User> getData() {
        ArrayList<User> arr;

        arr = fromAPI(new VolleyCallBack() {
            @Override
            public ArrayList<User> onSuccess(ArrayList<User> result) {

                return result;
            }
        });
        return arr;
    }

}

如果您使用 android 组件 (mvvm) 最好在存储库和视图模型从存储库获取数据后在数据源中发出请求 mvvm

here is guide for mvvm