美文网首页
EventBus源码分析小结

EventBus源码分析小结

作者: Dane_404 | 来源:发表于2019-03-19 23:18 被阅读0次

1、EventBus.getDefault().register(this),getDefault()无非就是返回单例,所以直接看构造:

   //subscriptionsByEventType,按事件类型订阅,key为事件类型,也就是参数名,value为有这种事件类型的集合
   private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; 
   //typesBySubscriber,按订阅者类型,key为订阅者,value该订阅者的事件类型
   private final Map<Object, List<Class<?>>> typesBySubscriber;
   private final Map<Class<?>, Object> stickyEvents;
   public EventBus() {
    this(DEFAULT_BUILDER);   //DEFAULT_BUILDER就是EventBusBuilder 
   }

   EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10); //Handler
    backgroundPoster = new BackgroundPoster(this);  //对应background模式,实现了runnable
    asyncPoster = new AsyncPoster(this);  //对应async模式
    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;  //线程池
   }

接下来看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);  //这里是存储信息
        }
    }
    }

看这个方法subscriberMethodFinder.findSubscriberMethods(subscriberClass):

   //返回这个订阅者的方法集合
   List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {   //看有没缓存,没有再往下走
        return subscriberMethods;
    }

    if (ignoreGeneratedIndex) {  //默认是false
        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;
    }
    }

下面看下findUsingInfo:

   private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    FindState findState = prepareFindState();  //用来存储寻找过程的信息
    findState.initForSubscriber(subscriberClass);   //给findState.clazz赋值
    while (findState.clazz != null) {
         //上一步的ignoreGeneratedIndex作用就是在这里,但默认的为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();  //寻找父类,如果是Android原生的跳出循环
    }
    return getMethodsAndRelease(findState);
   }

findUsingReflectionInSingleClass(findState):

    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
        methods = findState.clazz.getMethods();
        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中
                        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");
        }
    }
    }

经过上面的方法查找,满足条件的方法信息会保存到FindState,那么回到上面的findUsingInfo最后的return getMethodsAndRelease(findState):

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

上面就很简单,返回的找到的符合的方法集合,到这里寻找订阅者方法走完,回到register的subscribe:

   //参数一是订阅者,二是订阅者的方法
   private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;  //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);
        }
    }
    }

2、注册事件流程就到这里,总结一下,注册流程会通过反射去找到订阅者对应的接收事件的方法,然后做相应的保存,接下来看post流程:

   /** Posts the given event to the event bus. */
   public void post(Object event) {
    //currentPostingThreadState是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;
        }
    }
   }

往下看 postSingleEvent:

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {  //Inheritance继承的意思
        //寻找事件的父类与接口,比如我发送TextView,那么如果是View也会接收到
        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()) {
        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;
   }

再往下postToSubscription,分为四种模式:

   private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    switch (subscription.subscriberMethod.threadMode) {
        case POSTING:
            invokeSubscriber(subscription, event);  //最终调用method invoke来执行订阅者的方法
            break;
        case MAIN:
            if (isMainThread) {
                invokeSubscriber(subscription, event); //主线程直接执行
            } else {
                mainThreadPoster.enqueue(subscription, event); //handler到主线程执行
            }
            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);
    }
   }

总之,事件的传递最终都是通过反射invoke调用对应订阅者对应的方法。从头到尾总结下,注册时,会通过反射找到这个订阅者所有符合条件的方法并存储起来,这里条件指的是注解和参数,然后发送消息会遍历存储的订阅者的信息,符合条件的通过反射直接调用对应的方法。

相关文章

网友评论

      本文标题:EventBus源码分析小结

      本文链接:https://www.haomeiwen.com/subject/hgoomqtx.html