初识 EventBus

2017-04-08  本文已影响0人  Arnold_J

EventBus

官网:链接
版本:3.0.0


Get Started

compile 'org.greenrobot:eventbus:3.0.0'
public class MessageEvent {
    // 事件中需要传递的内容
    public final String message;
 
    public MessageEvent(String message) {
        this.message = message;
    }
}
@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}
@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent  event){
        Toast.makeText(this, "onMessageEvent == "+event.mMessage, Toast.LENGTH_SHORT).show();
    }
EventBus.getDefault().post(new MessageEvent  ("this is a message event"));

Delivery Thread ( ThreadMode )

EventBus 可以在内部处理线程操作,处理事件的线程可以和发送事件的线程不同,这个特性最常见的应用是对于UI的操作。在 Android 中,UI 操作必须在 UI 线程中进行;在另一方面,网络操作或者其他耗时操作则不能在 UI 线程上操作以免造成 ANR。EventBus 会帮助我们在不同线程上处理这些任务,与此对应,我们只需要在订阅方法上 填写不同的 ThreadMode 即可。

// Called in the same thread (default)
// ThreadMode is optional here
@Subscribe(threadMode = ThreadMode.POSTING)
public void onMessage(MessageEvent event) {
    log(event.message);
}
// Called in Android UI's main thread
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(MessageEvent event) {
textField.setText(event.message);
}
// Called in the background thread
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
    saveToDisk(event.message);
}
// Called in a separate thread
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessage(MessageEvent event){
    backend.send(event.message);
}

Configutation

EventBus 利用构建者模式进行创建:

// 全部可设置属性:[链接](http://greenrobot.org/files/eventbus/javadoc/3.0/org/greenrobot/eventbus/EventBusBuilder.html)
EventBus eventBus = EventBus.builder()
    .logNoSubscriberMessages(false)
    .sendNoSubscriberEvent(false)
    .build();

EventBus#getDefault 获得的对象是双重校验的单例,能确保在不同线程中也只存在一个 EventBus 的实例。但 EventBus 的构造方法是公有的,因此利用构建者模式创建的对象并非单例。

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}
/** 
  * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a 
  * central bus, consider {@link #getDefault()}.
  */
public EventBus() {
    this(DEFAULT_BUILDER);
}

如果希望修改默认 EventBus 单例对象,需要通过以下代码:

EventBus.builder()
      .throwSubscriberException(BuildConfig.DEBUG) // 修改属性
      .installDefaultEventBus();

Sticky Event 粘滞事件

特点:
1.先发送再订阅后,可以接收到订阅事件
2.对于同一个事件,只保存最近一次的数据

发送事件:

EventBus.getDefault().postSticky(new Event_Message("this is a message event "));

接收事件:

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onMessageEvent(Event_Message event){
    Toast.makeText(this, "onMessageEvent == "+event.mMessage, Toast.LENGTH_SHORT).show();
}

移除事件:

MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class);
// Better check that an event was actually posted before
// 暂时没有找到相关方法,是在事件类中添加一个 flag 属性?
if(stickyEvent != null) {
    // "Consume" the sticky event
    EventBus.getDefault().removeStickyEvent(stickyEvent);
    // Now do something with it
}
// EventBus.getDefault().removeAllStickyEvents(); // 移除所有粘滞事件

Priorities and Event Cancellation 优先级和事件取消

事件默认优先级为 0,数字越大,优先级越高,优先级高的订阅方法可以取消优先级低的订阅方法。

// Called in the same thread (default)
@Subscribe
public void onEvent(MessageEvent event){
    // Process the event
    ...
    // Prevent delivery to other subscribers
    EventBus.getDefault().cancelEventDelivery(event) ;
}

Events are usually cancelled by higher priority subscribers. Cancelling is restricted to event handling methods running in posting thread


Subscriber Index

是 EventBus 3.0 特有的东西,让它能通过注解的方式获取对象,获取不到的才利用反射的方式。
gradle 2.2.0 以上版本用下面的方式就可以了:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ]
            }
        }
    }
}
 
dependencies {
    compile 'org.greenrobot:eventbus:3.0.0'
    annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}

混淆

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

扩展阅读:
源码解析:http://ms.csdn.net/geek/101429
其他:http://www.cnblogs.com/whoislcj/p/5595714.html

上一篇下一篇

猜你喜欢

热点阅读