EventBus原理

分析版本

implementation 'org.greenrobot:eventbus:3.2.0'
复制代码

基本使用

第一步

定义一个用于承载信息的类java

data class MessageEvent (val age:String,val name:String)
复制代码

第二步

在接收信息的Actvit或者Fragment的onCreate中进行注册git

EventBus.getDefault().register(this)
复制代码

在onDestroy中解除注册github

EventBus.getDefault().unregister(this)
复制代码

并定义一个接收方法安全

@Subscribe(threadMode = ThreadMode.MAIN)
fun onMessageEvent(event: MessageEvent?) {
    Log.d("EventBus","${event?.name}")
}
复制代码

第三步

在发送信息的类中发送markdown

val messageEvent = MessageEvent("10", "Bob")
EventBus.getDefault().post(messageEvent)
复制代码

完成app

原理分析

register

先从注册开始看起异步

EventBus.getDefault().register(this)
复制代码

getDefault方法就不看了,就是一个单例返回一个EventBus对象,看register方法async

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

虽然代码看上去寥寥几行但其关联的信息仍是至关丰富的,先来看subscriberMethodFinder.findSubscriberMethods(subscriberClass),其功能主要就是将注册类的接收事件方法经过反射获取其参数类型,线程模式,优先级等并保存起来。ide

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }

    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;
    }
}
复制代码

一开始就先判断是否有保存过的SubscriberMethod列表,有就直接返回没有则会向下执行。ignoreGeneratedIndex默认构造参数为fasle,因此接下来看findUsingInfo方法,以下函数

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    FindState findState = prepareFindState();
    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);
}
复制代码

先是经过prepareFindState方法获取FindState对象,代码比较简单就不贴了。调用initForSubscriber方法存入注册类的class对象并初始化其中的一些变量。findState.subscriberInfo = getSubscriberInfo(findState); 第一次调用EventBus时subscriberInfo都是为null,这里我们暂时略过回头再看。接下来是findUsingReflectionInSingleClass(findState),先简单了解一下FindState对象,看一下他的成员变量。它是SubscriberMethodFinder的一个静态内部类。

static class FindState {
    final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
    final Map<Class, Object> anyMethodByEventType = new HashMap<>();
    final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
    final StringBuilder methodKeyBuilder = new StringBuilder(128);

    Class<?> subscriberClass;
    Class<?> clazz;
    boolean skipSuperClasses;
    SubscriberInfo subscriberInfo;
复制代码

看一下findUsingReflectionInSingleClass方法,他就是主要实现反射过程的方法

private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        // This is faster than getMethods, especially when subscribers are fat classes like Activities
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
        try {
            methods = findState.clazz.getMethods();
        } catch (LinkageError error) { // super class of NoClassDefFoundError to be a bit more broad...
            String msg = "Could not inspect methods of " + findState.clazz.getName();
            if (ignoreGeneratedIndex) {
                msg += ". Please consider using EventBus annotation processor to avoid reflection.";
            } else {
                msg += ". Please make this class visible to EventBus annotation processor to avoid reflection.";
            }
            throw new EventBusException(msg, error);
        }
        findState.skipSuperClasses = true;
    }
    for (Method method : methods) {
        int modifiers = method.getModifiers();
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    if (findState.checkAdd(method, eventType)) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException("@Subscribe method " + methodName +
                        "must have exactly 1 parameter but has " + parameterTypes.length);
            }
        } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            throw new EventBusException(methodName +
                    " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }
}
复制代码

首先是经过注册类的Class对象反射出他的Methods,而后循环判断方法修饰符的Int值是否知足运行条件,知足的话获取这个方法的参数类型,参数个数为一个时反射他的注解类对象。看一下findState.checkAdd这个方法主要是判断是否存入过相同的Method。

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);
    }
}
复制代码

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;
    }
}
复制代码

这两个方法主要是将新的Method存入anyMethodByEventType变量以及在anyMethodByEventType变量中被相同key替换掉的Method存入subscriberClassByMethodKey变量中。这个不理解也不要紧并不影响你理解EventBus的原理,你就当他默认返回true就好了。 而后就是从注解对象中获取他的线程模式,优先级,以及Method和eventType参数类型,将这些包装成一个SubscriberMethod对象,存入FindState对象的列表中。
看到这里先给你们整理一下思路,如图
//TODO 占位~~~~(先空着后面我补充,这导图软件不太好用)

接下来看一下register方法中的subscribe(subscriber, subscriberMethod) 方法:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    CopyOnWriteArrayList<Subscription> 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;
        }
    }

    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);
        }
    }
}
复制代码

首先是先从包装好的subscriberMethod对象中获取方法的参数类型,并将注册对象subscribersubscriberMethod包装到Subscription对象中,Subscription类比较简单里面就存入了这两变量再有几个比较函数就不贴代码了。
subscriptionsByEventType.get(eventType)
其泛型Map<Class<?>, CopyOnWriteArrayList> subscriptionsByEventType,这个变量比较重要须要关注一下,他在EventBus的构造函数中初始化过,它的key值为注册类接收事件方法的入参的Class类。从这个Map中获取的List为Null的时候会new一个List(CopyOnWriteArrayList就是一个线程安全的List没必要太过关注),不为Null时则会根据索引和优先级的判断将包装好的newSubscription加入到这个List中。

typesBySubscriber.get(subscriber)

其泛型Map<Object, List<Class<?>>> typesBySubscriber,也是在构造函数中初始化过。逻辑和上面同样不细说了,这个Map存入的key值为注册对象,value为值为注册类接收事件方法的入参的Class类为泛型的List。剩下的代码为EventBus的粘性事件处理,这里暂时就先不说了后面说完post的代码你就懂了。

post

如今开始分析EventBus.getDefault().post(messageEvent)

public void post(Object event) {
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    if (!postingState.isPosting) {
        postingState.isMainThread = isMainThread();
        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;
        }
    }
}
复制代码

首先看一下currentPostingThreadState.get()

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

ThreadLocal是一个避免线程冲突的机制,简单来讲就是为每一个线程都设置了单独的变量。找了一个连接供你们参考ThreadLocal
它的泛型为PostingThreadState,EventBus的一个静态内部类比较简单,你们都能看懂我就很少说了。

final static class PostingThreadState {
    final List<Object> eventQueue = new ArrayList<>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}
复制代码

post() 方法中,前面的东西都很一目了然我就不废话了,从postSingleEvent(eventQueue.remove(0), postingState) 开始

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) {
            logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}
复制代码

入参时eventQueue.remove(0) 就是把要发送的第一个Event移除,返回值也就是移除的event。eventInheritance的默认值为true,进入到lookupAllEventTypes(eventClass) 方法。

private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
    synchronized (eventTypesCache) {
        List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
        if (eventTypes == null) {
            eventTypes = new ArrayList<>();
            Class<?> clazz = eventClass;
            while (clazz != null) {
                eventTypes.add(clazz);
                addInterfaces(eventTypes, clazz.getInterfaces());
                clazz = clazz.getSuperclass();
            }
            eventTypesCache.put(eventClass, eventTypes);
        }
        return eventTypes;
    }
}
复制代码

eventTypesCache.get(eventClass)
private static final Map<Class, List>> eventTypesCache = new HashMap<>(); key值为post进去的Event的Class对象,value是一个泛型为class的List。这个List中放入的是这个Enevnt的Class对象及它的基类的Class对象还有它实现的接口及接口基类的Class对象。 addInterfaces(eventTypes, clazz.getInterfaces()); 就是将接口及其基类的Class加入到List中。

static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
    for (Class<?> interfaceClass : interfaces) {
        if (!eventTypes.contains(interfaceClass)) {
            eventTypes.add(interfaceClass);
            addInterfaces(eventTypes, interfaceClass.getInterfaces());
        }
    }
}
复制代码

从lookupAllEventTypes返回一个list后开启循环调用postSingleEventForEventType(event, postingState, clazz) ,入参分别为从Post传入的event事件,postingState对象,和class对象。第一次循环时这个Class就是event事件的class对象。

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted;
            try {
                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;
}
复制代码

好的这下重点来了,还记得这个变量么subscriptionsByEventType,在register过程当中这个变量的key值存入的为接收事件方法的入参的Class类,vlaue值为一个List其泛型包装了注册类对象及接收事件方法的各类属性。因此在这里用postSingleEventForEventType方法中传入的class在这个变量中拿出对应注册类中的接收事件方法,经过反射调用这个接收事件方法并将event传入就能够实现通讯了。

接下来看postToSubscription(subscription, event, postingState.isMainThread) 方法,第一个参数中包含了注册类对象及接收事件方法的各类属性,第二个参数为要传递的event事件,第三个判断是否为主线程

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 MAIN_ORDERED:
            if (mainThreadPoster != null) {
                mainThreadPoster.enqueue(subscription, event);
            } else {
                // temporary: technically not correct as poster not decoupled from subscriber
                invokeSubscriber(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);
    }
}
复制代码

这里经过判断接收事件的线程模式来执行对应的方法,先看主线程Main的同步调用invokeSubscriber(subscription, event)

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);
    }
}
复制代码

就是直接经过反射来调用方法传入event参数很简单。

如今来看异步mainThreadPoster.enqueue(subscription, event)

为了使你们思路贯穿,简单看一下mainThreadPoster哪来的

mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
复制代码
@Override
public Poster createPoster(EventBus eventBus) {
    return new HandlerPoster(eventBus, looper, 10);
}
复制代码
public class HandlerPoster extends Handler implements Poster {

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

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

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            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;
        }
    }
}
复制代码

很明显使用Handle来完成线程通讯的,Poster接口也就enqueue一个函数。PendingPost也只是包装了一下Subscription和Event方便造成队列来循环调用,在enqueue方法中调用sendMessage,在handleMessage中接收判断后再调用eventBus.invokeSubscriber(pendingPost)

void invokeSubscriber(PendingPost pendingPost) {
    Object event = pendingPost.event;
    Subscription subscription = pendingPost.subscription;
    PendingPost.releasePendingPost(pendingPost);
    if (subscription.active) {
        invokeSubscriber(subscription, event);
    }
}
复制代码

最后再反射调用就完成了

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);
    }
}
复制代码

很简单。 到此EventBus源码分析完毕。EventBus的源码体量并不大,结构也并不复杂,非常适合来培养本身的源码阅读能力和分析能力。

相关文章
相关标签/搜索