EventBus源码详解

1.简介

EventBus 是一个在 Android和Java上使用的 事件发布/订阅框架,通过解耦发布者和订阅者简化 Android 事件传递,事件传递既可用于 Android 四大组件间通讯,也可以用户异步线程和主线程间通讯等等。
相比传统Handle,Interface回调,BroadCastReceiver等。EventBus的优点是代码简介,使用简单,并将事件发布和订阅充分解耦。

2.简单使用

@Override
protected void onStart() { //订阅
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
protected void onStop() { //取消订阅
    super.onStop();
    EventBus.getDefault().unregister(this);
}


@Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 1)
public void onMessageEvent(MsgEvent event) { //响应方法
    Toast.makeText(this, event.message, Toast.LENGTH_SHORT).show();
}

3.类详解

EventBus的创建(单例 + Builder )

public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }
    public EventBus() {
        this(DEFAULT_BUILDER);
    }
    EventBus(EventBusBuilder builder) {
    }

单例+Build方式很常见,EventBus构造方法一般在单例中为private,在这使用public的意义在于让用户可自己构建EventBus 新建的EventBus和默认的实例发布和订阅事件都是相互隔离的,互不干扰。新建一个EventBus:

EventBus mEventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();

3.1订阅逻辑

  1. 先找订阅者A下所有订阅方法。
  2. 以A订阅的事件类型为分别key,A+A的订阅方法(key类型)为value放进subscriptionsByEventType Map中
  3. 以A类名为key,A中的订阅方法参数类型为value放入typesBySubscriber Map中
  4. 如果是订阅了粘滞事件的订阅者,从粘滞事件缓存区获取之前发送过的粘滞事件,响应这些粘滞事件。
    来自CodeKK分析EventBus订阅流程图
    EventBus源码详解_第1张图片
    订阅流程.png
    public void register(Object subscriber) {
        Class subscriberClass = subscriber.getClass();
        //找到该类下所有订阅方法。(被Subscribe注解标识的方法)
        List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //把类和方法关联起来
                subscribe(subscriber, subscriberMethod);
            }
        }
    }
    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //发送事件类型,比如是String
        Class eventType = subscriberMethod.eventType;
       //把订阅者和方法组合成一个对象Subscription 。
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
       //把订阅了指定类型(如String)的Subscriptions 放进subscriptionsByEventType中
       //如订阅了String类型的有什么类,这些类中有什么方法。
       CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        //typesBySubscriber包含了一个类订阅了那些类型事件
        //如TestActivity有两个响应方法,一个事件是String,一个是int
        List> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
        //是sticky方法则取出对应的sticky事件post给当前方法
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List).
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, Object> entry : entries) {
                    Class candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

3.2发送&响应事件

  1. 从ThreadLocal中取出当前事件分发封装对象PostingThreadState,从该对象中取出发送事件的事件队列,把要post的事件加入此队列。
  2. 如果PostingThreadState不是正在发送事件,则不断从队列中取出事件。分发给订阅了此事件的方法。
    3.根据每个响应方法的ThreadMode不同,采用不同的Poster响应事件。

来自CodeKK分析EventBus Post流程图

EventBus源码详解_第2张图片
Post流程.png

3.2.1ThreadMode 的5种类型。

  1. POSTING: 默认的ThreadMode 类型,表示在post线程直接执行响应订阅方法,不管是主线程还是子线程。所以在主线程时不能有时不能有耗时操作。

  2. MAIN:在主线程响应订阅方法,如果post在主线程则直接响应,如果不是则加入队列用Handler处理消息,适合必须在主线程处理事件,所以不能做耗时操作

  3. MAIN_ORDERED:和MAIN类似,但是不会根据post是否在主线程做出响应,而是直接加入队列用Handler处理,确保Post调用不会阻塞。

  4. BACKGROUND:如果post不在主线程,则直接响应方法,在主线程则加入队列使用BackgroundPoster处理消息。这里是启动唯一的后台线程处理响应方法,事件多了就会阻塞等待前面事件完成。所以使用场景为:操作轻微耗时且不会过于频繁,即一般的耗时操作都可以放在这里

  5. ASYNC:不论post在哪个线程,直接使用线程池中的空闲线程处理。和BACKGROUND不同,这里不会阻塞。适合耗时操作

3.2.2分析下BackgroundPoster的"唯一"线程

enqueue时会用synchronized 锁住当前BackgroundPoster 对象,必须前面的事件处理完了才能继续处理下个事件。虽然是用的线程池处理事件。但是在某一时刻只有唯一的一个线程在处理事件。

final class BackgroundPoster implements Runnable, Poster {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

    private volatile boolean executorRunning;

    BackgroundPoster(EventBus eventBus) {
        this.eventBus = eventBus;
        queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) { //等待。
            queue.enqueue(pendingPost);
            if (!executorRunning) {
                executorRunning = true;
                eventBus.getExecutorService().execute(this); //处理事件
            }
        }
    }

    @Override
    public void run() {
        try {
            try {
                while (true) {
                    //最多等1s
                    PendingPost pendingPost = queue.poll(1000); 
                    if (pendingPost == null) {
                        synchronized (this) {
                            // Check again, this time in synchronized
                            pendingPost = queue.poll();
                            if (pendingPost == null) {
                                executorRunning = false;
                                return;
                            }
                        }
                    }
                    eventBus.invokeSubscriber(pendingPost);
                }
            } catch (InterruptedException e) {
                eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
            }
        } finally {
            executorRunning = false;
        }
    }

}

AsyncPoster 则是并行执行的,每个事件直接入队用空闲线程处理。

class AsyncPoster implements Runnable, Poster {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

    AsyncPoster(EventBus eventBus) {
        this.eventBus = eventBus;
        queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

    @Override
    public void run() {
        PendingPost pendingPost = queue.poll();
        if(pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        }
        eventBus.invokeSubscriber(pendingPost);
    }

}

3.2.3看下发送Sticky事件

也是调用post,但之前先把事件添加进缓存。对应在register时,保存订阅方法时,如果该方法时sticky的。则要从stickyEvents取出事件执行该方法。所以这刚注册的方法也能执行之前发送的消息,完成粘性功能。

    public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }

4.主要成员变量含义

查看地址

EventBus源码详解_第3张图片
变量含义.png

5.使用EventBus可优化点

  1. 开启索引,可以在寻找订阅方法时不适用反射,提升效率
    开启索引
EventBus mEventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();
//寻找订阅者里的方法。
 List findSubscriberMethods(Class subscriberClass) {
        List subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) { //默认false
           //反射
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
           //从MyEventBusIndex找,找不到用反射
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
  1. eventInheritance是否使用事件继承,默认为true。
    例如:B继承与A,发送事件B会也发送A。
    可以关闭设置为false。提升性能。

你可能感兴趣的:(EventBus源码详解)