美文网首页收藏
EventBus源码详解

EventBus源码详解

作者: 天上飘的是浮云 | 来源:发表于2022-04-10 21:54 被阅读0次

EventBus笔记

一、EventBus使用

EventBus使用有四步骤:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //1.1 在OnCreate()方法中注册
        EventBus.getDefault().register(this)
    }

    //2. 定义事件接收方法以@Subscribe来注解
    //必需是public类型,不能是static、abstract修饰,
        //并且参数只能是一个
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleEvent(dd: String){
        Log.i("EventBus",dd)
    }
    
    fun onClickListener(){
        //3. 系统任意位置发送事件
        EventBus.getDefault().post("ff")
        EventBus.getDefault().postSticky("dd")
    }

    override fun onDestroy() {
        super.onDestroy()
        //页面退出时,注销监听者
        EventBus.getDefault().unregister(this)
    }

二、Eventbus.getDefault().register()注册

注册

1、Eventbus.getDefault()返回一个Eventbus单列

    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

2、调用EventBus的register方法

 public void register(Object subscriber) {
     //2.1 通过SubscriberMethodFinder.findSubscriberMethods找到类中
     //被@Subscribe注解的方法,被@Subscribe注解的方法,参数
     //不能超过一个、必须是public方法,不能是static 、abstract的方法
     Class<?> subscriberClass = subscriber.getClass();
     List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
     synchronized (this) {
         for (SubscriberMethod subscriberMethod : subscriberMethods) {
             //2.2 通过subscribe方法
             subscribe(subscriber, subscriberMethod);
         }
     }
 }
//通过找到@Subscribe注解的方法
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.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");
        }
    }
}

2.2 通过subscribe()方法来将subscriber和subscriberMethod封装为一个Subscription实例;并通过eventType也就是接收方法参数的类型,在subscriptionsByEventType中找到该类型对应的Subscription集合(subscriptions)。并将新的newSubscription根据priority插入到合适的位置;

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        //1. 通过subscribe()方法来将subscriber和subscriberMethod封装为一个Subscription实例;
        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);
            }
        }
        
        //2. 并通过eventType也就是接收方法参数的类型,
        //在subscriptionsByEventType中找到该类型对应的Subscription集合(subscriptions)。
        //并将新的newSubscription根据priority插入到合适的位置;
        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);
        
        //3. 如果接收方法定义为粘性的,就找到对应的粘性事件,
        //并通过checkPostStickyEventToSubscription(newSubscription, stickyEvent);发送事件,
        //调用subscription.subscriberMethod.method.invoke(subscription.subscriber, event)
        //来将事件调用到被@Subscribe注解的方法
        //这里详细后面再说
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                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.3 如果接收方法定义为粘性的,就找到对应的粘性事件,并通过checkPostStickyEventToSubscription(newSubscription, stickyEvent);发送事件,调用subscription.subscriberMethod.method.invoke(subscription.subscriber, event)来将事件调用到被@Subscribe注解的方法

    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
            // --> Strange corner case, which we don't take care of here.
            postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
        }
    }

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

    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.getDefault().post()发送事件

3.1 从currentPostingThreadState中取出当前线程的PostingThreadState实例,currentPostingThreadState是一个ThreadLocal,在调用postSingleEvent()方法

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

    public void post(Object event) {
        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;
            }
        }
    }

3.2 调用了postSingleEventForEventType()方法

    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) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

3.3 从subscriptionsByEventType取出事件类型对应的Subscription列表,并调用postToSubscription方法将事件分发给它们

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

3.4 这里上面注册时,如果是粘性事件的话也会将粘性事件最终通过这个postToSubscription方法发送出去,这里细说一下,

ThreadMode有四种类型:

  • POSTING:默认类型,在当前线程中直接发送事件,如果当前是子线程就在子线程中发送事件,如果是主线程就在子线程中发送事件
  • MAIN:指定在主线程中发送事件,如果当前线程是主线程就直接发送,如果当前线程是子线程,那就切换到主线程发送事件(如何切换后面在细说)
  • BACKGROUND:指定在子线程中发送事件,如果当前线程是主线程就通过线程池去执行,如果是子线程就直接发送事件(它需要等待事件处理,然后在取出下一个事件发送,所以不能处理耗时操作)
  • ASYNC:通过线程池来处理事件,它不等待事件执行完成,直接将队列中的事件,全部发送出去。
    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        //1. 通过@Subscribe注解时指定的线程模型来区分不同发送方式,默认为Posting类型
        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);
        }
    }

3.5 这几个ThreadMode最终都是通过invokeSubscriber方法来执行发送事件,它是通过subscriberMethod里参数method来反射调用执行。

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

3.6 ThreadMode.MAIN模式如果在子线程如何切换到主线程?

    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            ...
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            ...
        }
    }

它是通过MainThreadPoster,它实际上是继承于Handler的HandlerPoster对象,调用它的enqueue(方法,将subscription和Event封装为PendingPost,并发送一个空消息,交给handleMessage处理,然后交给了 eventBus.invokeSubscriber(pendingPost);来执行。超过10毫秒后,再发送空消息,直到队列为空

//实例化的时候将 Looper.getMainLooper()传了进去,那么这就是一个在主线程创建的Handler
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);

final class HandlerPoster extends Handler {

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

3.7 ThreadMode.BACKGROUND模式如果在如何在主线程切换到子线程执行?

case BACKGROUND:
    if (isMainThread) {
        backgroundPoster.enqueue(subscription, event);
    } else {
        invokeSubscriber(subscription, event);
    }
    break;

通过调用backgroundPoster.enqueue()方法,它继承于Runnable。并通过EventBus的executorService来执行,在run方法中,每1000毫秒从队列中取出,通过eventBus.invokeSubscriber执行。线程池默认是newCachedThreadPool (它的核心线程数为0,非核心无限大,工作队列为SynchronousQueue,用该线程池执行,直接会开启线程或者复用空闲线程执行)

private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

final class BackgroundPoster implements Runnable {

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

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

}

3.8 ThreadMode.ASYNC模式如果在如何处理事件?它和BackgroundPoster不同在于run方法中,BackgroundPoster是通过while循环来等待上一个事件执行完成后,在发送下一个事件,而AsyncPoster则直接全部将队列中的事件发送出去,不需要阻塞等待事件处理完成。它适合耗时的操作,如网络请求等操作。(在enqueue方法中也不一样,BackgroundPoster是通过executorRunning控制,而AsyncPoster则来一个事件,就丢进线程池中执行。

class AsyncPoster implements Runnable {

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

    @Override
    public void run() {
        PendingPost pendingPost = queue.poll();
        if(pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        }
        eventBus.invokeSubscriber(pendingPost);
    }

}

四、发送 粘性事件,与普通事件不同的是将事件载入stickyEvents缓存中,在下一次有粘性事件监听者注册时,将相应的粘性事件发送给他。

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

五、注销监听

注销就没啥好说的了,就是将有关该监听者相关信息移除的工作。

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

相关文章

网友评论

    本文标题:EventBus源码详解

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