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的源碼體量並不大,結構也並不複雜,非常適合來培養本身的源碼閱讀能力和分析能力。

相關文章
相關標籤/搜索