Android面试框架源码-EventBus源码初探

  1. EventBus.getDefault().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);
        }
    }
}

这个方法会得到 Activity或者Fragment的class, 然后以class 为key 把所有用@Subscribe标记的方法找到保存在一个Map集合中。

List findSubscriberMethods(Class subscriberClass) {
    List subscriberMethods = METHOD_CACHE.get(subscriberClass);
    //....省略

    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    if (subscriberMethods.isEmpty()) {
        //....省略
    } else {
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}

一个class 对应一个List 然后遍历List把每个SubscriberMethod 封装成对应的new Subscription(subscriber, subscriberMethod)同时得到eventType (就是@Subscribe注解方法的参数类型) class ,从另一个map中取出一个ArrayList 然后把新的Subscription放在这个list集合中,同时还回去判断他是否是sticky 。

// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    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;
        }
    }

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

至此所有的订阅者都保存在subscriptionsByEventType map集合中,key是被订阅方法参数类型的class,value是一个订阅方法集合Subscription,Subscription内包含有Activity 或者Fragment的class 以及 对应的SubscriberMethod.

  1. EventBus.getDefault().post(message)
    它会首先从ThreadLocal 中拿到当前线程 判断是主线城还是子线程,然后获取到当前线程的线程队列,把消息内容添加进去。最后循环执行postSingleEvent
public void post(Object event) {
   //从ThreadLocal 中拿到当前线程信息
    PostingThreadState postingState = currentPostingThreadState.get();
    //并把消息添加到这个线程的消息队列中
    List 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 {
            //循环去post队列中的消息
            while (!eventQueue.isEmpty()) {
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

在发送消息的时候他还会 获取消息类型的父类以及接口类的class,最后挨个寻找这些Class对应的Subscription ,从subscriptionsByEventType map集合取出来,调用postToSubscription 方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {
        //获取当前消息类型的父类 class以及接口class
        //比如post是ArrayList  那么他还会获取到List类型的SubscriberMethod
        List> 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);
    }
    // 省略。。。
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
    CopyOnWriteArrayList subscriptions;
    synchronized (this) {
        //从上一步中的map中取出对应的EventType subscriptions
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        //遍历执行发送消息的方法
        //Subscription 身上自带 SubscriberMethod和Subscriber订阅者
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted = false;
            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;
}

最后根据subscriberMethod.threadMode以及当前所在线程然后判断如何发送消息

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

总结

EventBus 通过注册方法,将观察者保存起来,这个过程做了两件是,第一件是观察者身上的所有@subscribe 注解注释的方法封装成一个SubscribeMethod保存在一个集合中,一个Activity或者Fragment对应一个List 然后遍历这个集合拿到所有的SubscribeMethod的方法的参数类型的class。根据这个class 去另外一个集合中获取一个list集合subscriptionsByEventType,这个集合是 一个回调方法参数类型对应一个List。 其中Subscription 传入了两个参数一个是Activity或者fragment实例一个是对应的SubscribeMethod。 如果找不到就创建一个list 保存。
EventBus.post(Object object)方法根据上文的判断,post的参数类型至关重要的, 他首先拿到object这个类相关的所有类型,包括父类还有实现的接口,保存在一个list集合中。然后遍历这个集合,根据class 从上面的subscriptionsByEventType集合中去取对应的List ,这个Subscription 上文也说过,他包含了 Activity /fragment的实例,还有SubscribeMethod信息。有了这些就可以反射调用实例的指定method方法了。
如何进行线程的切换?
在EventBus中会保存一个ThreadLocal实例,通过这个实例就能获取到当前线程的信息PostingThreadState,在这个线程状态信息中维护了很多信息,其中有个就是List集合队列,里面就是这个线程post 的所有信息。然后开启一个while循环不断的去post消息,post的过程中就是获取这个object的所有相关类(父类和接口),遍历根据class从subscriptionsByEventType缓存中找到对应的Subscription。根据subscription.subscriberMethod.threadMode 调用对应的线程切换方法。如果 post方法是在子线程 ,那么会先把消息放到一个队列中然后通过handler发送消息,开启while循环,不停的invokeSubscriber

你可能感兴趣的:(源码分析)