流行框架源码分析(1)-EventBus3.0源码解析

主目录见:Android高级进阶知识(这是总目录索引)
 因为国庆放假的缘故,好几天没有写文章,今天抽空来写一篇,那我们就从我们平常用的比较熟悉的框架开始讲解,今天讲解一款比较熟悉的框架EventBus3.0,在实际项目用的也比较多,废话不多说,直接开始。

国庆快乐

一.目标

今天写这篇主要是从源码角度来讲解一个流行框架的原理,使用方法我就不讲了,因为比较简单,那么我们今天的目标很明确:
1.从源码角度了解EventBus的用法;
2.通过源码来学习一个开源项目可能用到的技术点。

二.源码分析

我们知道我们EventBus3.0的用法分为创建,注册,发送,粘性事件和后面加入的索引。今天我们将从一个一个开始讲。为了后面说的时候比较顺利呢,我们先说下索引的作用下。

1.Subscriber Index

如果要用到索引的话我们需要在gradle文件里面添加如下:

buildscript {
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}
apply plugin: 'com.neenbedankt.android-apt'
 
dependencies {
    compile 'org.greenrobot:eventbus:3.0.0'
    apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}
apt {
    arguments {
        eventBusIndex "com.example.myapp.MyEventBusIndex"
    }
}

这是典型的apt的配置,当然现在一般框架用的annotationProcessor的方式,其实也是一样的,都差不多。这里的配置主要是用来生成放置一个索引类的,我们使用的时候会这样使用:

 EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();        //开启加速模式

当然这是其中的一种使用方法。我们不去看其他的方式主要我们看到这个地方索引是用addIndex方法加入的,这里面的MyEventBusIndex是哪里生成的呢?其实这个地方就是用的apt的方式生成的(包名和类名是根据上面gradle里面配置的)。首先我们来看生成的文件长什么样:

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(com.example.zz.eventbusnewdemo.MainActivity.class, true,
                new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEvent", com.example.zz.eventbusnewdemo.event.FirstEvent.class, ThreadMode.MAIN,
                    60, false),
        }));

        putIndex(new SimpleSubscriberInfo(com.example.zz.eventbusnewdemo.ThirdActivity.class, true,
                new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onStickyEvent", com.example.zz.eventbusnewdemo.event.StickyEvent.class,
                    ThreadMode.MAIN, 0, true),
        }));

        putIndex(new SimpleSubscriberInfo(com.example.zz.eventbusnewdemo.SecondActivity.class, true,
                new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onSecondEvent", com.example.zz.eventbusnewdemo.event.FirstEvent.class,
                    ThreadMode.POSTING, 1000, false),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

这个类其实很简单,就是调用putIndex方法将类与类对应的订阅信息放进Map里面。因为这些方法是放进static中的,所以在new的时候就会调用了。具体这个类怎么生成我到时会在编译期注解那里说到,代码主要在源码中的下图位置:

Processor

2.创建

我们知道我们一个类要想成为订阅者必须在类中注册:

  EventBus.getDefault().register(this);

所以我们很自然来看getDefault()方法是干了什么:

   /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

这里就是获取EventBus的实例,这里使用了单例的模式。那么我们这里接着就是看EventBus的构造函数了:

 public EventBus() {
        this(DEFAULT_BUILDER);
    }

我们看到这里EventBus的构造函数是public的,也就是说我们可以自己去实例化一个EventBus,所以也就是说允许多个EventBus,然后独立处理自己的事件,但是如果通过getDefault()方法创建的话,因为是使用单例模式进行创建,所以只会有一个EventBus实例。我们继续看这里this调用了另外一个构造函数:

    EventBus(EventBusBuilder builder) {
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

我们看到这个类里面实例化了好多类,首先我们看下以下几个:

   private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    private final Map<Class<?>, Object> stickyEvents;

subscriptionsByEventType:这个类主要是key为event,value为Subscription的集合,Subscription是个封装的类,里面主要有订阅者和订阅类两个类,这个map主要是在发送的时候根据event来查找订阅者的。
typesBySubscriber:这个类主要是key为订阅者,value为event,主要是注册的时候会用到。
stickyEvents:这个方法主要保存粘性事件的。
这些都会在后面讲到,所以大家放心,如果这个地方还不知道他们是干嘛用的。然后我们来看下面几个Poster:

  private final HandlerPoster mainThreadPoster;
    private final BackgroundPoster backgroundPoster;
    private final AsyncPoster asyncPoster;

这几个Poster在ThreadMode和粘性事件的时候都会用到。主要是线程有关。另外我们看构造函数里面下面一些都是用builder给EventBus的属性赋值,这里主要是通过建造者的设计模式给builder构造不同的功能。我们可以通过builder构造如下:

  eventBus = EventBus.builder().eventInheritance(false).build();

具体的建造者有哪些这里不展开讲了。我们有用到可以看下很简单。

3.注册

注册的话主要是关联订阅者和订阅方法,3.0以后的话订阅方法支持注解@Subscribe,注解的话支持配置如下:

注解

支持配置线程模式,是否是粘性事件,优先级。然后我们会调用register()方法来进行注册:

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

我们看到首先我们是查找订阅者对应的订阅方法(一个订阅者对应多个订阅方法),然后就行订阅。首先我们看findSubscriberMethods方法干了些什么:

  List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//首先从缓存中查找订阅者对应的订阅方法,如果有则直接返回即可
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
//是否忽略索引功能,这个地方3.0用来加速的,我们不忽略,要想忽略可以通过builder进行设置
        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            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;
        }
    }

从我们注释可以看到这里的ignoreGeneratedIndex为false即不忽略索引功能,所以我们会走到findUsingInfo方法里面,我们看下这个方法到底是做了什么:

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//这里首先准备一个FindState对象,这个类主要保存了订阅者信息
        FindState findState = prepareFindState();
//用订阅者类初始化findState对象
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
//获取订阅者信息,如果开启了索引功能就不会为空否则会为空
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                findUsingReflectionInSingleClass(findState);
            }
//向上往父类进行查找
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

上面我们看到一个FindState类,我们来看看FindState类主要有哪些信息呢?

 static class FindState {
//订阅方法列表
        final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
//key为event,value为Method,主要后面checkAdd方法会用到
        final Map<Class, Object> anyMethodByEventType = new HashMap<>();
//用方法和event生成的key,value为订阅类,这个在checkAddWithMethodSignature方法里面会用到
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class<?> subscriberClass;
        Class<?> clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;
.......
}

我们看到这里面FindState保存了订阅者和订阅方法以及在检查的方法里面会用到,我们程序调用findState.initForSubscriber(subscriberClass)就是将FindState的属性赋值如下:

 void initForSubscriber(Class<?> subscriberClass) {
            this.subscriberClass = clazz = subscriberClass;
            skipSuperClasses = false;
            subscriberInfo = null;
        }

我们看到这个地方其实只有订阅者被赋值了。所以循环会走进去。然后我们看到getSubscriberInfo方法,这个方法具体是做了什么呢,看返回知道返回的是订阅的信息,那是怎么得到:

    private SubscriberInfo getSubscriberInfo(FindState findState) {
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

我们知道我们第一个subscriberInfo是空的所以判断不成功,第二个判断的subscriberInfoIndexes 是什么呢?这个其实就是 List<SubscriberInfoIndex> 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;
    }

也就是说了添加了索引这个subscriberInfoIndexes才不会为空,不然将返回null,显然我们这里是能得到的,因为编译期我们已经putIndex了,文章的开篇就说了,不知道可以返回回去看下。
所以我们findUsingInfo方法就会继续走到获取订阅信息里面的所有方法,然后调用findState的checkAdd方法:

        boolean checkAdd(Method method, Class<?> eventType) {
            // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
            // Usually a subscriber doesn't have methods listening to the same event type.
            Object existing = anyMethodByEventType.put(eventType, method);
            if (existing == null) {
                return true;
            } else {
                if (existing instanceof Method) {
                    if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                        // Paranoia check
                        throw new IllegalStateException();
                    }
                    // Put any non-Method object to "consume" the existing Method
                    anyMethodByEventType.put(eventType, this);
                }
                return checkAddWithMethodSignature(method, eventType);
            }
        }

首先我们看下程序是检验event对应的订阅方法存不存在(put方法将value放置进去的同时会返回一个旧值,也就是说已经有event对应的方法就会返回)如果是没有订阅过的直接返回true。不然接着判断程序走到checkAddWithMethodSignature方法:

  private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            Class<?> methodClass = method.getDeclaringClass();
            Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
            if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                // Only add if not already found in a sub class
                return true;
            } else {
                // Revert the put, old class is further down the class hierarchy
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }

这个方法也不难看懂,这个方法首先是拼接了方法名和事件名称作为key,然后将订阅者作为value放置进去,如果是第一次的话那肯定返回是null,程序就返回true,但是这个订阅方法已经有对应的话,那么会接着判断
methodClassOld.isAssignableFrom(methodClass),意思就是说旧的注册过的订阅者是否是新的订阅者的父类或者同个类,如果是的话还是返回ture即这是个新的订阅者,需要添加。那么到底这两个方法(checkAdd,checkAddWithMethodSignature)适用的场景是什么呢?

场景一:假如一个类里面有多个订阅方法,而这些方法的方法名是一样的,但是参数不一样即接收的事件不一样,那么在checkAdd中的existing不为null,会到checkAddWithMethodSignature中,这个方法里面又会根据方法名和事件名进行作为key判断,显然这个地方拼接的key在这种情况下是不同的。方法返回true,所以也就是说,允许一个类有多个参数不同的相同方法。

场景二:这里假设两个类有继承关系,B类继承了A类,B类中重写了A类中的订阅方法,那么在checkAdd方法中的exiting不为null,会到checkAddWithMethodSignature中,显然这个地方因为方法名和事件名是一样的,所以methodClassOld 不为空,然后会判断isAssignableFrom,由于B不是A类的父类,所以这里会返回false,也就是说A类里面的订阅方法不会被通知到了。所以子类重写父类的订阅方法,那么父类的订阅方法就失效了,显然这也是符合设计思想的。

接着我们回到findUsingInfo方法,程序会接着走到最后一句getMethodsAndRelease方法:

  private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        findState.recycle();
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                if (FIND_STATE_POOL[i] == null) {
                    FIND_STATE_POOL[i] = findState;
                    break;
                }
            }
        }
        return subscriberMethods;
    }

首先我们会得到findstate对象里面的订阅方法,然后将findstate放进缓存池里面。最后程序返回订阅类对应的订阅方法集合,这样我们程序回到EventBus的register()方法里面,我们程序调用了subscribe方法:

   // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
//首先将订阅者和订阅的方法封装到SubSciption中
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根据event获取对应的Subsciption        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
//如果为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;
            }
        }
//根据订阅者来获取订阅的事件集合,如果还没有就创建然后放进去
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
//判断订阅方法是粘性的,如果是粘性的会直接就发送,后面也会详细做说明
        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);
            }
        }
    }

到这里我们注册的流程已经讲解完毕,我们这里做个总结:
在注册的时候,会先查找这个订阅类对应于哪几个订阅方法,这里面会判断是要从索引里面查找还是反射进行遍历然后找到符合条件的方法,查找的时候会通过checkAdd和checkAddWithMethodSignature方法进行筛选。找到订阅类对应的订阅方法然后就遍历订阅方法调用subscibe方法放进subscriptions集合中。

4.发送

发送事件的时候我们一般会调用如下代码:

 EventBus.getDefault().post(new FirstEvent("Post Content"));

所以我们直接来看EventBus的post方法:

  public void post(Object event) {
//从ThreadLocal中获取一个PostingThreadState 
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
//将事件添加进事件队列中
        eventQueue.add(event);

        if (!postingState.isPosting) {
//判断是否在主线程中
            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;
            }
        }
    }

程序第一句会获取PostingThreadState对象,那currentPostingThreadState到底是啥呢,我们可以看看:

private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

我们看到这里new出这个对象,然后get的时候会从ThreadLocal中获取,也就是说这个对象是线程安全的,如果不同的线程这个对象是不同的。然后我们程序会调用postSingleEvent方法:

 private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
//eventInheritance这个可以在builder中设置,这个标志的意思是是否考虑继承关系,
//如果考虑的话那么如果事件继承自父类,那么父类也会作为事件被发送
        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集合
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            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,传的参数我们已经说明了,我们可以具体来看这个方法干了啥:

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

这个方法很简单有没有,根据threadMode线程模式来判断要怎么调用。如果是POSTING则会直接调用invokeSubscriber,如果是MAIN但是在主线程也会调用invokeSubscriber,如果是BACKGROUND,但是不在主线程也会调用invokeSubscriber,不然就会调用几个poster进行进队列。首先我们看下invokeSubscriber:

 void invokeSubscriber(Subscription subscription, Object event) {
        try {
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }

这个方法很简单呀,就是利用反射进行对方法进行调用。然后我们看看其他的用poster进行调用的。首先我们看下mainThreadPoster(是个HandlerPoster):

final class HandlerPoster extends Handler {
//待发送的post队列
    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();
    }
........
}

这个类里面有PendingPostQueue 是个链表的结构,链表里面的节点PendingPost包括了event和subscription,这个poster主要是threadMode为MAIN然后不在主线程时候调用,我们看enqueue做了啥:

   void enqueue(Subscription subscription, Object event) {
//根据subscription和event来构建PendingPost对象
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
//加入队列中
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
//用handler来发送消息
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

这个方法主要是获取到PendingPost对象然后加入队列,接着发送消息。由于这个Handler初始化的时候new HandlerPoster(this, Looper.getMainLooper(), 10)是传入主线程的Looper,所以这个是运行在ui线程的:

 @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
//死循环,不断从队列中取出PendingPost
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
//接着调用这个方法,这样的话这个方法就是在主线程的
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }

我们看到,这个方法就是取出队列里面的PendingPost然后进行正常的invokeSubscriber。这样的话就是在主线程运行了。接着我们就看看backgroundPoster:

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

我们看到这个方法里面也是有一个PendingPostQueue,跟HandlerPost是一样的,这个BackgroundPoster实现了Runnable接口,其他没有什么,我们来看enqueue方法:

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

我们看到这个方法前面都一样,就最后调用了 eventBus.getExecutorService().execute(this)执行了这个线程,所以接下来会调用这个线程的run方法:

 @Override
    public void run() {
        try {
            try {
                while (true) {
                    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) {
                Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
            }
        } finally {
            executorRunning = false;
        }
}

我们看到这个run方法里面也是取出队列中的PendingPost然后调用invokeSubscriber方法,也就是说这个方法是运行在子线程中的。最后我们看AsyncPoster,这个我就不认真说了,其实和BackgroudPoster是类似的,只是没有判断是不是有一条线程正在运行,就是说每次运行都是在不同的线程。

5.取消

我们注册事件之后,没有用的时候要取消,即我们会调用方法如下:

EventBus.getDefault().unregister(this);

所以我们直接就来看看unregister是做了什么呢?

  /** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
//根据订阅者来获取事件
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
//遍历所有的事件
for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
//移除
            typesBySubscriber.remove(subscriber);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

我们找到订阅者对应的事件集合,然后遍历之后调用unsubscribeByEventType,那我们就直接看看这个方法做了啥:

  private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根据事件获取订阅者信息
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
//取出订阅者然后判断是否跟要删除的订阅者相同,相同则删除
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

我们看到注销的流程是很简单的,从typesBySubscriber和subscriptionsByEventType移除跟订阅者有关的信息。

6.粘性事件

粘性事件跟其他事件不同的是先发送出去,然后再注册接收到事件。粘性事件有时候还是很有用的。粘性的事件发送是通过postSticky方法来发送的,我们这里来看看:

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

我们看这个方法将事件为value和事件对应的class对象为key放进stickyEvents(Map)中,然后调用post事件,但是这时候因为还没有注册的话是找不到订阅者的,但是为什么在注册的时候又可以收到粘性事件呢?其实我们之前有看过,我们来看看:

   // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
//首先将订阅者和订阅的方法封装到SubSciption中
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根据event获取对应的Subsciption        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
//如果为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;
            }
        }
//根据订阅者来获取订阅的事件集合,如果还没有就创建然后放进去
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
//判断订阅方法是粘性的,如果是粘性的会直接就发送,后面也会详细做说明
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
//这个标志我们之前也说过,默认是true的
                // 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 {
//根据event获取特定的事件然后发送
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

EventBus并不知道当前的订阅者对应于哪个事件,所以要遍历一遍找到匹配的粘性事件,然后调用checkPostStickyEventToSubscription方法,这个方法就是调用的postToSubscription,就是根据threadMode调用相应的订阅方法,我们之前已经讲过了。好啦,到这里我们已经讲完了所有的源代码,收获还是很大的,有些知识技术点我们会一一讲解的。
总结:讲完EventBus3.0的源码,我们已经对于应用这个开源框架更有把握了,遇到问题我们也能轻易排除,所以收获还是很大的,最后祝大家国庆快乐哈。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容