问题
I'm starting using EventBus 3.0.0.
I'm having 3 sticky events to be sent from Service to Activity:
- action started
- action progress
- 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:
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
来源:https://stackoverflow.com/questions/38605322/is-greenrobot-eventbus-sticky-events-order-guaranteed