EventBus small tips

1. EventBus threading model

2. stickiness event

3. Configure confusing rules

.
.
.
.

Introduction of 0.EventBus

一个Android事件发布/订阅轻量级框架,
功能:通过解耦发布者和订阅者简化Android事件传递 [2] 
EventBus可以代替Android传统的Intent,Handler,Broadcast或接口函数,在Fragment,Activity,Service线程之间传递数据,执行方法。
特点:代码简洁,是一种发布订阅设计模式(观察者设计模式)。

.
.

1. EventBus threading model ThreadMode

Because Android strict limits on the thread, EventBus be correspondingly different threads of control. By specifying the thread pattern, we can control which subscribe to the callback function to run on a thread.
There are threaded mode:
POSTING : in which thread release stroke on the implementation in which
the MAIN : executed in the main thread, if the subscriber callback event is more time-consuming, the publisher of the subsequent instructions will be blocked.
MAIN_ORDERED : After the release of the follow-up instruction is executed immediately, not blocked subscriber callback events.
The BACKGROUND : In the background thread execution (non-UI thread), if the publisher in a non-UI thread, the subscriber will be in the same thread, the UI thread if the publisher, the subscriber creates a new thread, and that thread carried out.
ASYNC : whether the events published in which thread will execute in a separate thread to open. It can be time-consuming operation

2. stickiness event

In general we should be using sequential EventBus Subscriptions after release. But sticky events can be achieved after the first publication subscriptions.

3. Configure confusing rules

When we package generated APK, the system in order to make our packages as small as possible, you may remove some of the functions we did not use. In EventBus, the function of our subscription event is run by reflection, so the risk of being deleted, so we have to configure it confusing rules.
In proguard_rules.pro file, we add the following code:

#EventBus
-keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

Published 47 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41525021/article/details/104158087