2016-11-12 16 views
7

Tôi đang sử dụng EventBus để thông báo Activity/Fragment khi tôi nhận được phản hồi từ máy chủ. Mọi thứ hoạt động tốt cho đến nay, nhưng vấn đề phát sinh khi tôi tiêu thụ hai cuộc gọi mạng trong cùng một số Fragment hoặc Activity. Vấn đề là cùng một phương pháp onEvent(String response) nhận cuộc gọi cho cả hai câu trả lời từ máy chủ. Câu trả lời của call 1 khác với call 2.Cách sử dụng Loại cuộc gọi với EventBus

Tôi đã đưa ra giải pháp - Tôi đã thêm CallType vào NetworkReqest nhưng tôi không thể thông báo cho hoạt động/đoạn về cuộc gọi mạng vì post() chỉ nhận một tham số.

Đây là mã có liên quan -

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); 
    } 


} 

Method Bên trong fragment/activity Ở đây nảy sinh vấn đề khi sau khi nhận được phản hồi từ một yêu cầu tôi bắn một yêu cầu khác mà phụ thuộc của respose của yêu cầu đầu tiên

@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(); 
    } 

Tôi làm cách nào để phân biệt callType trong phạm vi onEvent(). Một số hướng dẫn là bắt buộc. Cảm ơn nhiều.

Trả lời

3

Một tùy chọn là bọc hai phần dữ liệu bạn cần vào một lớp và chuyển nó tới xe buýt sự kiện. Rời khỏi các thành viên tư nhân, getters/setters và constructors cho ngắn gọn.

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

Khi bạn nhận được một phản ứng, phân bổ một NetworkResponse và cư nó với phản ứng và các loại cuộc gọi và post đó đến xe buýt sự kiện.

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

} 
+0

Tôi đã suy nghĩ để làm điều đó nhưng tôi nghĩ rằng có thể có một số giải pháp tốt hơn so với điều này. –

1

Nối tiếp chuỗi phản ứng với hạt java trong phương pháp onResponse và phát ra đối tượng phù hợp với chế độ xem. Hoạt động, Phân đoạn và Chế độ xem không cần phải biết về tuần tự hóa và ngoài ra, hiệu suất của ứng dụng có thể cải thiện, vì bạn có thể sửa đổi mã của mình để tuần tự hóa dữ liệu trong chuỗi nền.

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); 
    } 

Sau đó, thuê bao sự kiện đầu tiên của bạn sẽ trông như thế này:

@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); 
     } 
    } 

và bạn có thể có một giây, khác nhau, String thuê bao. Nhưng kể từ khi bạn sẽ thực hiện cuộc gọi thứ hai anyway, nó sẽ là tốt nhất để thực hiện nó trực tiếp sau khi nhận được câu trả lời đúng từ một trong những đầu tiên.

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); 
    } 
} 

Cuối cùng, này hai dòng

boolean isCourseAvaible = false; 
     if (!isCourseAvaible) { 

là không cần thiết, cũng giống như không có điều kiện.

Các vấn đề liên quan