EventBus源码详解(三):高级使用

640 阅读7分钟
原文链接: www.jianshu.com

写在前面

EventBus是一个Android平台上基于事件发布和订阅的轻量级框架,可以对发布者和订阅者解耦,并简化Android的事件传递。

本文是关于EventBus系列文章的第三篇,相关文章有:

这篇是EventBus使用篇最后一篇,前面基本把EventBus的功能都介绍了,但还有一个很重要的功能:EventBus的创建和配置,这也是今天的主要介绍的。


正文

从前面的文章知道,EventBus不是单例的,它是可以无限创建实例的,也就是说我们可以自己创建适合自己需求的EventBus实例。EventBus的创建是使用了建造者模式,提供了一个EventBusBuilder给我们用链式调用的方式实现可自由搭配所要配置的功能。

好,先来看看EventBusBuilder给我们提供了哪些配置项(注意,下面的属性为了读者能更好理解,我调了下声明顺序和加了空行):

public class EventBusBuilder {
    boolean logSubscriberExceptions = true;        // 在订阅方法中抛出异常时, 是否打印日志, 默认为true
    boolean sendSubscriberExceptionEvent = true;   // 在非订阅SubscriberExceptionEvent事件方法中抛出异常时, 是否发送SubscriberExceptionEvent事件, 默认为true
    boolean throwSubscriberException;              // 在非订阅SubscriberExceptionEvent事件方法中抛出异常时, 是否抛出EventBusException异常, 默认为false

    boolean logNoSubscriberMessages = true;        // 没找到事件订阅方法, 是否打印日志, 默认为true
    boolean sendNoSubscriberEvent = true;          // 没找到事件订阅方法, 是否发送NoSubscriberEvent事件, 默认为true

    boolean eventInheritance = true;               // 发送子事件, 是否发送父事件, 默认为true

    /* 下面三个参数用在查找订阅方法 */
    boolean ignoreGeneratedIndex;                  // 是否用反射查找订阅方法, 默认为false
    boolean strictMethodVerification;              // 非注解生成索引时, 严格方法验证: 当方法不符合格式(public, non-abstract, non-static, non-briage, 只有一个参数)时, 是否抛出EventBusException异常, 默认为false
    List<SubscriberInfoIndex> subscriberInfoIndexes; // 注解生成的索引
    
    /* 默认线程数量不定的缓存线程池 */
    private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool(); 
    ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;

    List<Class<?>> skipMethodVerificationForClasses; // 这货根本没用, 没在源码中看到它使用...

    EventBusBuilder() {
    }

    ...
}

上面注释已经讲得非常详细了,上面的配置项在EventBusBuilder里除了subscriberInfoIndexes以外,都有一个同名方法来改变配置,而subscriberInfoIndexes的配置方法是addIndex

/** Adds an index generated by EventBus' annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
    if(subscriberInfoIndexes == null) {
        subscriberInfoIndexes = new ArrayList<>();
    }
    subscriberInfoIndexes.add(index);
    return this;
}

哈哈,如果看了我第二遍文章的应该知道这货了,它是在生成索引时,要手动给EventBus配置的,来回顾下:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // 加载索引,添加到默认配置的EventBus
        EventBus.builder().addIndex(new SampleBusIndex()).installDefaultEventBus();
    }
}

EventBusBuilder的配置项一般保持默认配置就可以了,下面重点挑几个比较重要的来举例说明下。

发送异常事件

EventBus在所订阅的方法抛出异常时,是默认会打印日志并发出异常事件SubscriberExceptionEvent(当然,你没在订阅者里订阅SubscriberExceptionEvent肯定会收不到)。下面来试验下:

public class SubscriberExceptionsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subscriber_exceptions);
        EventBus.getDefault().register(this);
    }

    public void post(View view) {
        EventBus.getDefault().post(new MsgEvent(""));
    }

    @Subscribe
    public void onMsgEvent(MsgEvent event) {
        if (TextUtils.isEmpty(event.getMsg())) {
            throw new IllegalArgumentException("Event msg can not be empty");
        }
        Log.i("TEST", "onMsgEvent --> " + event.getMsg());
    }

    @Subscribe
    public void onSubscriberExceptionEvent(SubscriberExceptionEvent event) {
        // 订阅方法抛出异常时, 会到这里
        Log.i("TEST", "onSubscriberExceptionEvent --> " + event.throwable.getMessage());
    }
}

上面代码在Activity里订阅了MsgEventSubscriberExceptionEvent,然后点击按钮post一个msg为空的MsgEvent事件,而在MsgEvent的订阅方法中,当msg为空时抛出异常。运行程序,打开logcat可以看到:

E/EventBus: Could not dispatch event: class com.leo.eventbus.sample3.MsgEvent to subscribing class class com.leo.eventbus.sample3.SubscriberExceptionsActivity
...
I/TEST: onSubscriberExceptionEvent --> Event msg can not be empty

从上面日志可以看到,在订阅方法中抛出异常时,即会打log,同时发送SubscriberExceptionEvent事件。如果你把throwSubscriberException配置为true,就会直接闪退了。

发送找不到订阅方法事件

“发送找不到订阅方法事件”听起来有点拗口... 它的意思是当在订阅者post个事件时,而没订阅该事件的订阅方法时,就会发送NoSubscriberEvent事件(同样的,如果没在订阅者里订阅NoSubscriberEvent肯定也收不到)。验证下:

public class NoSubscriberActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_no_subscriber);
        EventBus.getDefault().register(this);
    }

    public void post(View view) {
        EventBus.getDefault().post(new MsgEvent("Hello World"));
    }

    @Subscribe
    public void onNoSubscriberEvent(NoSubscriberEvent event) {
        // 在订阅者中没找到发送的订阅事件, 会到这里
        Log.i("TEST", "onNoSubscriberEvent --> " + ((MsgEvent) event.originalEvent).getMsg());
    }
}

上面代码在Activity里只订阅了NoSubscriberEvent事件,然后点击按钮post一个没订阅的MsgEvent事件,运行程序,打开logcat:

D/EventBus: No subscribers registered for event class com.leo.eventbus.sample3.MsgEvent
I/TEST: onNoSubscriberEvent --> Hello World
事件继承

所谓事件继承即当一个事件类继承于另一个事件,当发送该子事件时,如果订阅了父事件,也将会发送父事件。事件继承的开关是eventInheritance,一切都没有代码来的直观:

public class EventInheritanceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_inheritance);
        EventBus.getDefault().register(this);
        EventBusManager.getEventBus(EventBusManager.NO_EVENT_INHERITANCE_TYPE).register(this);
    }

    public void post(View view) {
        EventBus.getDefault().post(new ErrMsgEvent("I am a error msg"));
    }

    @Subscribe
    public void onMsgEvent(MsgEvent event) {
        Log.i("TEST", "onMsgEvent --> " + event.getMsg());
    }

    @Subscribe
    public void onErrMsgEvent(ErrMsgEvent event) {
        Log.i("TEST", "onErrMsgEvent --> " + event.getMsg());
    }
}

上面代码在Activity里同时订阅了MsgEventErrMsgEvent事件,然后点击按钮post一个ErrMsgEvent事件。ErrMsgEvent是继承于MsgEvent的类:

public class ErrMsgEvent extends MsgEvent {
    ErrMsgEvent(String errMsg) {
        super(errMsg);
    }
}

再次运行程序,查看logcat:

I/TEST: onErrMsgEvent --> I am a error msg
I/TEST: onMsgEvent --> I am a error msg

可以看到,发送了子事件ErrMsgEvent,同时也会发送父事件MsgEvent。我觉得这个功能会对代码的可读性和理解在一定程度上造成影响。例如我订阅了一个父事件来更新UI,使我的账号的状态改为“在线”状态,而有个子事件是把账号改成“离线”状态,当你post子事件想把状态改成“离线”时,会发现无法成功。当然,也没人这么傻,如此使用,这里只是举例。我的意思是,当你还不很理解“事件继承”的用途时,最好先把它关掉,即把eventInheritance设置为false

其他配置

其他配置没啥好说了,保持默认就可以。需要提醒注意的是:

1. 订阅方法格式
订阅方法一定满足以下条件:

  • public修饰
  • 只有一个事件类参数
  • 非静态方法
  • 非抽象方法
  • 非桥接方法

如果你使用了注解,在不满足上面条件时,会在编译期就会报错,无法编译,因为在索引生成时,apt会检测上面前3个条件是否满足。如果没使用注解,是不会去检测的,也就相当于你没订阅该方法,那么就会收不到所订阅的事件了。当然,前面文章也说明了使用索引的优势,效率高出几倍,我们没理由不用注解,也就不怕订阅不满足条件的方法了。

2. 线程池
EventBus的默认线程池是数量不定的缓存线程池,也就是说,如果你稍不注意,过多地新开线程来发送事件的话,就有可能造成OOM。幸好的是,EventBus可以让我们自己实现线程池。

EventBus实例配置

上面关于EventBusBuilder的介绍已经讲解得非常详细了,相信大家能根据自己的需求来创建EventBus的实例。创建EventBus实例的入口是EventBus#builder().build()

/* EventBus */
public static EventBusBuilder builder() {
    return new EventBusBuilder();
}

可以看到,它是直接new个EventBusBuilder出来,然后就可以配置我们所需要的功能了。EventBus实例可以无限创建,但我们不可能这么做,我们只需创建我们需要的就可以了。我们可以使用简单工厂方法来选择创建我们需要的EventBus实例:

public class EventBusManager {

    public static final int NO_EVENT_INHERITANCE_TYPE = 1;
    public static final int FIXED_THREAD_TYPE = 2;

    /**
     * 事件非继承订阅EventBus
     */
    private static EventBus noEventInheritanceEventBus;

    /**
     * 固定线程池EventBus
     */
    private static EventBus fixedThreadEventBus;

    public static EventBus getEventBus(int type) {
        EventBus eventBus = EventBus.getDefault();
        switch (type) {
            case NO_EVENT_INHERITANCE_TYPE:
                if (noEventInheritanceEventBus == null) {
                    // lazy
                    synchronized (EventBusManager.class) {
                        if (noEventInheritanceEventBus == null) {
                            noEventInheritanceEventBus = EventBus.builder()
                                    .eventInheritance(false)
                                    .build();
                        }
                    }
                }
                eventBus = noEventInheritanceEventBus;
                break;

            case FIXED_THREAD_TYPE:
                if (fixedThreadEventBus == null) {
                    // lazy
                    synchronized (EventBusManager.class) {
                        if (fixedThreadEventBus == null) {
                            fixedThreadEventBus = EventBus.builder()
                                    .executorService(Executors.newFixedThreadPool(20))
                                    .build();
                        }
                    }
                    eventBus = fixedThreadEventBus;
                }
                break;
        }

        return eventBus;
    }
}

最后提醒注意:每个EventBus的实例都是独立的,也就是说,每个EventBus post的事件,只有使用该EventBus注册的订阅者才能接受到,其他EventBus注册的是无法接收的。


写在最后

终于写完EventBus的使用了,想不到如此轻量级的开源框架需要用三篇文章来讲解,看来要讲清楚各个细节真的不容易。三篇文章基本涵盖了EventBus的全部内容了,后续文章将会从源码来分析EventBus


demo