Is Greenrobot EventBus sticky events order guarant

2019-09-05 21:01发布

I'm starting using EventBus 3.0.0.

I'm having 3 sticky events to be sent from Service to Activity:

  1. action started
  2. action progress
  3. action finished

i'm listening to the events on main thread:

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

The service sends events in order: started-progressN-..-progressM-finished and the subscribed Activity updates the UI according to the events.

After the activity is rotated i expect to get sticky events in the order they were sent as otherwise it breaks the ui (since on started sets the progress to 0). Is events order guaranteed by EventBus (assuming i'm using the same EventBus, same receiver thread, same subscriber for all these events)?

According to my tests it's not guaranteed and it's the feature/issue, is it?

before rotation:

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%

after rotation (sticky events resent):

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

1条回答
成全新的幸福
2楼-- · 2019-09-05 21:32

I haven't tried it but documentation here says you can indicate a priority for every onEvent method.

Guessing you have 3 event classes such as CompilationStart, CompilationProgress and CompilationFinish, you can provide a priority of 3, 2 and 1 respectively as bellow. Anyway, remember that default priority is 0, so any other event will be received before all of these ones:

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

On the other hand you can avoid using priority if you just use one class such as CompilationInfo being this as follows:

public class CompilationInfo {
    public CompilationState compilationState;
    public int priority

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

Where CompilationState is a parent class that CompilationStart, CompilationProgress and CompilationFinish hinerits from. It would be even better if you use an enum for priority field as it is more readable. This way you only need one onEvent method.

EDIT: Changed priority values according to documentation changes

查看更多
登录 后发表回答