使用 EventBus 或 Otto 时减少事件数量 类

Reducing number of event classes when using EventBus or Otto

我即将开始开发 Android 应用程序。我有兴趣在我的应用程序中使用 Otto 或 EventBus 来协助进行异步 REST 网络调用并在调用有 returned.The 时通知主线程 我在研究期间发现使用这些总线的一个主要缺陷是通常需要创建的事件太多 类。是否有任何模式或方法可以减少必须使用的事件 类 的数量?

概念

我解决事件过多问题的最好方法 classes 是使用 Static Nested Classes 您可以阅读更多关于他们 here.

现在使用上面的概念来解决问题:

所以基本上假设您有一个名为 Doctor 的 class,您正在使用它来创建一个您在应用程序中传递的对象。但是,您想通过网络发送相同的对象并在同一对象的上下文中检索 JSON 并将其反馈给订阅者以进行处理。您可能会创建 2 classes

  1. DoctorJsonObject.java,其中包含有关返回的 JSON 数据和
  2. 的信息
  3. DoctorObject.java 包含您在应用中传递的数据。

你不需要那样做。 改为这样做:

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

现在你有一个医生 Class 封装 post 到网络的事件和从 post 返回的事件网络。

  1. Doctor.JSONData表示从网络返回的数据,格式为Json。

  2. Doctor.AppData 表示在应用程序中传递的“模型”数据。

要为 post 事件使用 class' AppData 对象:

/*
 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"));
}

您实现中的订阅者侦听此对象并发出 http 请求和 returns 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
            }
        });
    }
}

通过上述实现,您已将所有 Doctor 对象相关事件封装在 ONE Doctor class 中,并使用 static inner 在不同时间访问您需要的不同类型的对象classes。更少 class 结构更多。