【问题标题】:Is Greenrobot EventBus sticky events order guaranteed?Greenrobot EventBus 粘性事件顺序是否得到保证?
【发布时间】:2016-07-27 06:30:55
【问题描述】:

我开始使用EventBus 3.0.0。

我有 3 个粘性事件要从 Service 发送到 Activity:

  1. 动作开始
  2. 动作进度
  3. 动作完成

我正在监听主线程上的事件:

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void on...Event(... event) {
...
}

服务按顺序发送事件:started-progressN-..-progressM-finished,订阅的 Activity 根据事件更新 UI。

活动旋转后,我希望按照发送的顺序获取粘性事件,否则会破坏 ui(因为在开始时将进度设置为 0)。 EventBus 是否保证事件顺序(假设我对所有这些事件使用相同的 EventBus、相同的接收线程、相同的订阅者)?

根据我的测试不能保证这是功能/问题,是吗?

旋转前:

07-27 11:27:55.254  27910-27910/ app D/App﹕ status Compilation started ...
07-27 11:27:55.254  27910-27910/ app D/App﹕ compile progress 0%
07-27 11:27:55.354  27910-27910/ app D/App﹕ compile progress 20%
07-27 11:27:55.354  27910-27910/ app D/App﹕ compile progress 30%
07-27 11:27:55.354  27910-27910/ app D/App﹕ compile progress 40%
07-27 11:27:55.844  27910-27910/ app D/App﹕ compile progress 50%

旋转后(重新发送粘性事件):

07-27 11:27:59.554  27910-27910/ app D/App﹕ compile progress 50%
07-27 11:27:59.554  27910-27910/ app D/App﹕ status Compilation started ...

【问题讨论】:

  • 而且您的status 事件与您的progress 事件不同,对吧?
  • 它们是不同的类

标签: android event-bus greenrobot-eventbus-3.0


【解决方案1】:

我没有尝试过,但文档 here 说您可以为每个 onEvent 方法指定优先级。

假设您有 3 个事件类,例如 CompilationStart、CompilationProgress 和 CompilationFinish,您可以分别提供 3、2 和 1 的优先级,如下所示。无论如何,请记住默认优先级为 0,因此任何其他事件都会在所有这些事件之前收到:

@Subscribe(priority = 3);
public void onEvent(CompilationStart event) {
    ...
}
@Subscribe(priority = 2);
public void onEvent(CompilationProgress event) {
    ...
}
@Subscribe(priority = 1);
public void onEvent(CompilationFinish event) {
    ...
}

另一方面,如果您只使用一个类,例如 CompilationInfo,则可以避免使用优先级,如下所示:

public class CompilationInfo {
    public CompilationState compilationState;
    public int priority

    public CompilationInfo(CompilationState compilationState, int priority) {
        this.compilationState = compilationState;
        this.priority = priority;
    }
}

其中 CompilationState 是 CompilationStart、CompilationProgress 和 CompilationFinish 的父类。如果您使用枚举作为优先级字段会更好,因为它更具可读性。这样你只需要一个 onEvent 方法。

编辑:根据文档更改更改优先级值

【讨论】:

  • 好像是我需要的,去检查确认一下
  • 谢谢。但是自您的回答以来,文档可能已经更改。现在它说:“..优先级较高的订阅者将在其他优先级较低的订阅者之前收到事件。默认优先级是 0...”。应该是:开始 = 3,进度 = 2,完成 = 1
  • 谢谢@Simon Schubert,在您发表评论时,我已经更改了回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
相关资源
最近更新 更多