当我从服务器得到响应时,我正在使用EventBus通知Activity / Fragment.到目前为止,一切都运行良好,但是当我在相同的Fragment或Activity中使用两个网络调用时会出现问题.问题是onEvent(String response)获取来自服务器的两个响应的调用方法.呼叫1的响应与呼叫2不同.
我提出了一个解决方案 – 我在NetworkReqest中添加了CallType但是我无法通知活动/片段有关网络调用,因为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); } }
片段/活动内部的方法这里出现问题,当从一个请求获得响应后,我触发另一个请求,该请求取决于第一个请求的响应
@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(); }
如何区分onEvent()中的callType.需要一些指导.非常感谢.
解决方法
一种选择是将您需要的两个数据包装到一个类中并将其传递给事件总线.为了简洁起见,离开私人会员,吸气者/制定者和建设者.
class NetworkResponse() { public String callType; public String response; }
当您收到响应时,分配NetworkResponse并使用响应和呼叫类型填充它并将其发布到事件总线.
@Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(NetworkResponse networkResponse) { if(networkResponse.callType.equals(CALL_1)) { // ... } else if (networkResponse.callType.equals(CALL_2)) { // ... } }