Pay*_*arr 6 rest android otto greenrobot-eventbus
我即将在Android应用上开始开发.我有兴趣在我的应用程序中使用Otto或EventBus来协助进行异步REST网络调用,并在调用返回时通知主线程.我在研究过程中发现使用这些总线的一个主要缺陷是有通常需要创建太多的事件类.是否有任何模式或方法来减少必须使用的事件类的数量?
我解决了太多事件类问题的最好方法是使用静态嵌套类您可以在这里阅读更多关于它们的信息.
因此,基本上假设您有一个名为Doctor的类,您正在使用它创建一个与您的应用程序一起传递的对象.但是,您希望通过网络发送相同的对象,并在同一对象的上下文中检索JSON,并将其反馈给订阅者以执行某些操作.你可能会创建2个类
你不需要这样做. 而是这样做:
public class Doctor{
static class JSONData{
String name;
String ward;
String id;
//Add your getters and setter
}
static class AppData{
public AppData(String username, String password){
//do something within your constructor
}
String username;
String password;
//Add your getters and setters
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您有一个Doctors Class,它将发布到网络的事件和从网络发回的事件封装起来.
Doctor.JSONData表示以Json格式从网络返回的数据.
Doctor.AppData表示在应用程序中传递的"模型"数据.
要使用类'AppData对象,然后使用post事件:
/*
You would post data from a fragment to fetch data from your server.
The data being posted within your app lets say is packaged as a doctor
object with a doctors username and password.
*/
public function postRequest(){
bus.post(new Doctor.AppData("doctors_username","doctros_password"));
}
Run Code Online (Sandbox Code Playgroud)
您实现中的订阅者侦听此对象并发出http请求并返回Doctor.JSONData:
/*
retrofit implementation containing
the listener for that doctor's post
*/
@Subscribe
public void doctorsLogin(Doctor.AppData doc){
//put the Doctor.JSONObject in the callback
api.getDoctor(doc.getDoctorsName(), doc.getPassWord(), new Callback<Doctor.JSONObject>() {
@Override
public void success(Doctor.JSONObject doc, Response response) {
bus.post(doc);
}
@Override
public void failure(RetrofitError e) {
//handle error
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
通过上面的实现,您已经在ONE Doctor类中封装了所有与Doctor Object相关的事件,并使用静态内部类在不同时间访问了您需要的不同类型的对象.更少的类更多的结构.
| 归档时间: |
|
| 查看次数: |
1098 次 |
| 最近记录: |