EventBus源码解析

1、EventBus定义:
是一个发布 / 订阅的事件总线。
这么说应该包含4个成分:发布者,订阅者,事件,总线。
那么这四者的关系是什么呢?
很明显:订阅者订阅事件到总线,发送者发布事件。
大体应该是这样的关系:
这里写图片描述

2、EventBus的特点:
a).简化了组件之间的通信
b).将事件发送方和接收方执行与Activities, Fragments和后台线程,避免了复杂的和容易出错的依赖性和生命周期问题
c).包的体积很小(~ 50 k jar),
d).拥有先进的功能,如交付线程,用户优先级等。

3.EventBus的下载地址:
https://github.com/greenrobot/EventBus

4.源码解析:
预备军:
在讲源码之前,先把构造方法里面的三个比较重要的类说下;看能否猜到故事的结局…
1、HandlerPost

// 将事件发送到主线程执行的 handler。
final class HandlerPoster extends Handler {

    private final PendingPostQueue queue;
    private final int maxMillisInsideHandleMessage;
    private final EventBus eventBus;
    private boolean handlerActive;

    HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
        super(looper);
        this.eventBus = eventBus;
        this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
        queue = new PendingPostQueue();
    }

    void enqueue(Subscription subscription, Object event) {
        ...
    }

    @Override
    public void handleMessage(Message msg) {
       ...
    }
}

2、BackgroudPoster

// EventBus 内部有维护一个Executors.newCachedThreadPool 的线程池,当调用 BackGroudPost.enqueue 的时候,会将事件弄到线程池中执行。
// BackGroundPost是一个 Runnable, 内部维护一个队列,在 run 方法中会不断的从队列中取出 PendingPost,当队列没东东时,至多等待1s,然后跳出 run 方法。
final class BackgroundPoster implements Runnable {

    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) {
        ...
    }

    @Override
    public void run() {
        ...
    }

}

3、AsyncPoster

// AsyncPoster 的实现跟 BackgroundPoster 的实现极为类似,区别就是是否有在 run 方法中循环取出 PendingPost。
// 虽然相似,但是主要的不同点就是,asyncPost 会确保每一个任务都会在不同的线程中执行,而 BackgroundPoster 则如果发送的速度比较快且接收事件都是在 background 中,则会在同一线程中执行。

class AsyncPoster implements Runnable {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

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

    public void enqueue(Subscription subscription, Object event) {
       ...
    }

    @Override
    public void run() {
        ...
    }

}

大家都知道eventbus用的时候只需要注册一下:EventBus.getDefault().register(this);
然后就是post一下:EventBus.getDefault().post(param);
下面我们就研究一下register和post.
a)register
首先,EventBus.getDefault()就是个单例,双重锁的单例;(线程安全,性能佳)。

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

然后我们看一下register(this):

public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

可以看出首先获取订阅者的类对象
Class《?》 subscriberClass = subscriber.getClass();
然后调用内部类SubscriberMethodFinder的findSubscriberMethods方法,
传入了subscriber 的class,返回一个 List.
然后去遍历该类内部所有方法,去subscribe(匹配),下面看subscriberClass 类和findSubscriberMethods方法的代码:
subscriberClass 类:

/** Used internally by EventBus and generated subscriber indexes. */
public class SubscriberMethod {
    final Method method;//方法
    final ThreadMode threadMode;//执行线程
    final Class<?> eventType;//接收的事件类型
    final int priority;//优先级
    final boolean sticky;
    /** Used for efficient comparison */
    String methodString;

    public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
        this.method = method;
        this.threadMode = threadMode;
        this.eventType = eventType;
        this.priority = priority;
        this.sticky = sticky;
    }

    @Override
    public boolean equals(Object other) {
        ...
    }

    private synchronized void checkMethodString() {
        ...
    }

    @Override
    public int hashCode() {
        return method.hashCode();
    }
}

findSubscriberMethods方法:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);//首先从缓存中读取 
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //是否忽略注解器生成的MyEventBusIndex类
        if (ignoreGeneratedIndex) {
            //利用反射来获取订阅类中的订阅方法信息
            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、通过EventBusAnnotationProcessor(注解处理器)生成的MyEventBusIndex中获取
2、利用反射来读取订阅类中订阅方法信息
我们看到
METHOD_CACHE 的定义是一个线程安全的Hashmap。

 private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

接下来我们回到register,来看看
subscribe方法:

 // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        //优先级最高的。
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //把传入的参数封装成了一个Subscription
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();//没有则新建。
            // subscriptionsByEventType是一个Map这个Map其实就是EventBus存储方法的地方,一定要记住!
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }
        //实际上,就是添加newSubscription;并且是按照优先级添加的。可以看到,优先级越高,会插到在当前List的前面。
        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;
            }
        }
        //根据subscriber存储它所有的eventType 
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
//判断sticky;如果为true,从stickyEvents中根据eventType去查找有没有stickyEvent,如果有则立即发布去执行。       stickyEvent其实就是我们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<Class>).
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, 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);
            }
        }
    }

到此为止,请记住:
我们遍历了所有的方法,把匹配的方法最终保存在
subscriptionsByEventType(Map,key:eventType ; value:subscriptions )中;
eventType是我们方法参数的Class,
Subscription中则保存着subscriber, subscriberMethod(method, threadMode, eventType, priority);
接下来我们来看流程
post:

  /** Posts the given event to the event bus. */
    public void post(Object event) {
        //获取当前线程的postingState。PostingThreadState 会使用 ThradLocal 根据线程拿到当前线程的PostingThreadState。Handler也是使用的ThreadLocal这个变量。
        PostingThreadState postingState = currentPostingThreadState.get();
        //取得当前线程的事件队列
        List<Object> eventQueue = postingState.eventQueue;
        //将该事件添加到当前的事件队列中等待分发
        eventQueue.add(event);

        if (!postingState.isPosting) {
            //判断是否是在主线程post
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    //分发事件
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

下面来看事件是怎么分发的,postSingleEvent方法:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
           // 根据事件类型,取出自身以及父类、接口所有的类型。
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                // 执行发送,返回是否找到订阅者
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        if (!subscriptionFound) {
            if (logNoSubscriberMessages) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

接着看postSingleEventForEventType方法:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            // 取出订阅者并未 postingState 赋值。
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                     //根据subscription 接收事件的线程以及当前线程来发送事件。
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }

然后我们来看postToSubscription方法:

    // 方法指定的接收事件的线程,直接下结论:
    // 1.如果为 posting,则接收事件以及发送事件会在同一线程执行。
    // 2.如果为 mainThread,如果当前线程不是主线程,则会交给 mainThreadPoster 去执行,mainThreadPoster 是一个 handler,内部持有主线程的消息队列.
    // 3.如果为 background,如果当前是主线程,则交给 backgroundPoster 执行,进而交给 eventBus 的线程池执行,否则,将在同一线程执行。
    // 4.如果为 Async,则不管当前是啥线程,都交给 asyncPoster 执行,确保每一个任务都在不同的线程中。
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    invokeSubscriber(subscription, event);
                }
                break;
            case ASYNC:
                asyncPoster.enqueue(subscription, event);
                break;
            default:
                throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
        }
    }

诶呀,终于首尾照应了,跟之前的猜想一样的结局…. 是不是忒感动呀!
感动归感动,其实,总而言之,就是说:
register会把当前类中匹配的方法,存入一个map,而post会根据实参去map查找进行反射调用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值