如何使用EventBus使用Call Type

时间:2016-11-12 07:02:45

标签: android web-services android-fragments event-bus

当我收到服务器的回复时,我正在使用EventBus通知Activity/Fragment。到目前为止一切运行良好,但是当我在同一FragmentActivity中使用两个网络呼叫时会出现问题。问题是同一方法onEvent(String response)从服务器获取两个响应的调用。 call 1的回复与call 2不同。

我提出了一个解决方案 - 我在CallType中添加了NetworkReqest但我无法通知活动/片段有关网络呼叫的信息,因为post()只接受一个参数。

以下是相关代码 -

public class NetworkRequest {
    EventBus eventBus = EventBus.getDefault();

    public void stringParamRequest(String url, final Map<String, String> params,String callType) {
        StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        eventBus.post(response);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("volley", "Error: " + error.getMessage());
                eventBus.post(error);
            }
        }) {

            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> param = params;
                return param;
            }

        };
        SkillSchoolApplication.get().addToRequestQueue(jsonObjRequest);
    }

    public void stringRequest(String url, String callType) {
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                eventBus.post(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        SkillSchoolApplication.get().addToRequestQueue(stringRequest);
    }


}

fragment/activity内部的方法在从一个请求获得响应后,我发出另一个请求,这取决于第一个请求的停止

@Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String response) {
        Log.d(TAG, response);
        boolean isCourseAvaible = false;
        if (!isCourseAvaible) {
            isCourseAvaible = true;
            List<CoursesDTO> coursesDTOs = AppMgr.coursesMgr(response);
            String[] ids = new String[0];
            String id;
            if (coursesDTOs != null) {
                ids = new String[coursesDTOs.size()];
                for (int i = 0; i < coursesDTOs.size(); i++) {
                    ids[i] = coursesDTOs.get(i).getListId();

                }
            }
            id = TextUtils.join(",", ids);
            Map<String, String> map = new HashMap<>();
            map.put("part", "snippet,contentDetails");
            map.put("playlistId", id);
            map.put("key", AppConstants.YOUTUBE_KEY);
            NetworkRequest networkRequest = new NetworkRequest();
            networkRequest.stringParamRequest("some url", map);
        } else {
            Log.d(TAG, response);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(VolleyError error) {
        Log.d(TAG, error.toString());
        Toast.makeText(getActivity(), "Something went wrong " + error.toString(), Toast.LENGTH_SHORT).show();
    }

如何区分callType内的onEvent()。需要一些指导。非常感谢。

2 个答案:

答案 0 :(得分:3)

一种选择是将您需要的两个数据包装到一个类中并将其传递给事件总线。为简洁起见,不要让私人成员,吸气者/制定者和施工人员离开。

class NetworkResponse() {
   public String callType;
   public String response;
}

当你收到回复时,分配一个NetworkResponse并用响应和呼叫类型填充它,并将post填入活动总线。

@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(NetworkResponse networkResponse) {
  if(networkResponse.callType.equals(CALL_1)) {
     // ...
  } else if (networkResponse.callType.equals(CALL_2)) {
     // ...
  }

}

答案 1 :(得分:1)

在onResponse方法中将String响应序列化为java bean,并向视图发出正确的对象。活动,片段和视图无需了解序列化,此外,您的应用程序的性能可以提高,因为您可以修改代码以在后台线程中序列化数据。

public void stringRequest(String url, String callType) {
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                eventBus.post(AppMgr.coursesMgr(response));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        SkillSchoolApplication.get().addToRequestQueue(stringRequest);
    }

然后您的第一个活动订阅将如下所示:

@Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(List<CoursesDTO> coursesDTOs) {
        Log.d(TAG, response);
        boolean isCourseAvaible = false;
        if (!isCourseAvaible) {
            isCourseAvaible = true;
            String[] ids = new String[0];
            String id;
            if (coursesDTOs != null) {
                ids = new String[coursesDTOs.size()];
                for (int i = 0; i < coursesDTOs.size(); i++) {
                    ids[i] = coursesDTOs.get(i).getListId();
                }
            }
            id = TextUtils.join(",", ids);
            Map<String, String> map = new HashMap<>();
            map.put("part", "snippet,contentDetails");
            map.put("playlistId", id);
            map.put("key", AppConstants.YOUTUBE_KEY);
            NetworkRequest networkRequest = new NetworkRequest();
            networkRequest.stringParamRequest("some url", map);
        } else {
            Log.d(TAG, response);
        }
    }

您可以拥有第二个不同的String订阅。但是既然你要打第二个电话,最好在从第一个电话得到正确答案后直接执行。

public class NetworkRequest {
    EventBus eventBus = EventBus.getDefault();

    public void stringParamRequest(String url, final Map<String, String> params,String callType) {
        StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        eventBus.post(response);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("volley", "Error: " + error.getMessage());
                eventBus.post(error);
            }
        }) {

            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> param = params;
                return param;
            }

        };
        SkillSchoolApplication.get().addToRequestQueue(jsonObjRequest);
    }

    public void stringRequest(String url, String callType) {
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {  
              List<CoursesDTO> coursesDTOs = AppMgr.coursesMgr(response);
              String[] ids = new String[0];
              String id;
              if (coursesDTOs != null) {
                ids = new String[coursesDTOs.size()];
                for (int i = 0; i < coursesDTOs.size(); i++) {
                    ids[i] = coursesDTOs.get(i).getListId();

                }
              }
              id = TextUtils.join(",", ids);
              Map<String, String> map = new HashMap<>();
              map.put("part", "snippet,contentDetails");
              map.put("playlistId", id);
              map.put("key", AppConstants.YOUTUBE_KEY);
              NetworkRequest networkRequest = new NetworkRequest();
              networkRequest.stringParamRequest("some url", map);                   
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        SkillSchoolApplication.get().addToRequestQueue(stringRequest);
    }
}

最后,这两行

  boolean isCourseAvaible = false;
        if (!isCourseAvaible) {

是多余的,就像没有条件一样。