事件总线EventBus

解析EventBus

EventBus是一款针对Android发布的发布——订阅事件总线。EventBus三要素:

  • Event:事件,可以是任意类型的对象。
  • Subscribe:事件订阅者,3.0之后订阅者可以随便取名,需要添加注解@Subscribe。
  • Publisher:事件发布者,可以在任意线程任意位置发送事件,直接调用Post方法即可,可以使用自己实例化的EventBus对象。

EventBus的线程模型

  • POST类型:发布事件和接受事件在同一个线程,容易阻塞,要避免耗时操作。
  • MAIN类型:接收事件在UI线程中执行,事件处理的事件不能太长。
  • BACKGROUND类型:如果发布事件是在UI线程,那么接收事件开启子线程。如果发布事件是子线程,那么在当前线程执行。这种类型禁止进行UI更新操作。
  • ASYNC:无论事件在哪个线程发布,该事件处理函数都会在子线程中执行;同样,此事件处理函数禁止进行UI更新操作。

使用步骤

  • 自定义一个事件类
  • 在需要订阅事件的地方注册事件
  • 发送事件
  • 处理事件
  • 取消事件订阅

使用EvnentBus

首先配置gradle

implementation 'org.greenrobot:eventbus:3.0.0'

然后在MainActivty中实现事件注册功能将订阅者MainActivity注册到事件中去:

EventBus.getDefault().register(MainActivity.this);

实现事件取消功能,取消MainActivity的注册:

EventBus.getDefault().unregister(this);

对于订阅者,需要实现处理事件的方法:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
        tv_message.setText(messageEvent.getMessage());
    }

这里将发布的消息放在tv_message中去。使用@Subscribe注解,将threadMode设置成ThreadMode.MAIN模式,这样事件的处理就会放到主线程中执行。

然后需要一个事件的发布者,在发布者中通过

EventBus.getDefault().post(new MessageEvent("HELLO"));

来发布事件。

EventBus发布黏性事件

黏性事件就是发送事件之后再订阅该事件也能收到该事件。首先在MainActivity中对黏性事件做处理。

    @Subscribe(threadMode = ThreadMode.POSTING,sticky = true)
    public void onStickEvent(MessageEvent messageEvent){
        tv_message.setText(messageEvent.getMessage());
    }

在SecondActivity中发布黏性事件:

    bt_subscription.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(new MessageEvent("黏性事件"));
                finish();
            }
    });

源码解析EventBus

我们会使用EventBus.getDefault来获取EventBus实例,跟踪getDefault方法:

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

利用双重校验锁来得到单例,然后看EventBus的构造方法:

public EventBus() {
        this(DEFAULT_BUILDER);
    }

返回的是EvnetBusBuilder,此时调用了另一个构造方法,如下:

EventBus(EventBusBuilder builder) {
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        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;
    }

这里采用了建造者模式。

订阅者注册

接下来需要把订阅者注册到EventBus中去,看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);
            }
        }
    }

主要做了两件事,一件是查找订阅者的订阅方法,一件是遍历订阅方法,完成注册。在subscriberMethods中主要保存的是订阅方法的Method对象,线程模式,事件类型,优先级,是否是黏性事件等属性。接下来跟踪findSubscribeMethods方法,如下:

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

        if (ignoreGeneratedIndex) {
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);//3
        }
        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);//2
            return subscriberMethods;
        }
    }

首先从缓存中查找是否有订阅方法的集合,如果找到了立马返回,如果没有,则根据ignoreGeneratedIndex属性来选择采用何种方法来查找订阅方法的集合。由于我们一般用单例模式,这种情况下会进入注释3所在的方法:

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findState.subscriberInfo = getSubscriberInfo(findState);//1
            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);//3
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

如果没有配置索引,那么就会进入3中的方法,将订阅的方法保存在findState中,最后通过getMethodAndRelease方法对findState做回收处理并返回订阅方法的List集合,继续跟踪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();//1
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        ...
    }

主要在注释1中使用反射得到了订阅者中的所有方法,并根据方法的类型,参数,注解来找到订阅方法,找到订阅方法后将订阅方法相关信息保存在findState中。

订阅者的注册过程

回到register方法,其中在subcribe方法中对订阅方法进行了注册:

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//1
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//2
        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);//3
                break;
            }
        }

        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);//4
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

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

首先在注释1出根据订阅者和订阅方法创建一个订阅对象Subscription。在注释2处根据事件类型获取Subscriptions订阅对象集合。如果Subscriptions为null那么重新创建,并将Subscriptions根据eventType保存在subscriptionsByEventType这个map中,在注释3中按照订阅方法的优先级插入到订阅对象集合中,完成订阅方法的注册。注释4中通过subscriber获取subscribedEvnet(事件类型的集合),如果subscribedEvents为null,则重新创建,并将eventType添加到subscribedEvents中去。并根据subscriber将subscribedEvents存储在typesBySubscriber中。主要就是做了两件事,将subscriprions根据eventType封装到subscriptionByEventType中去,将subscribesEvent根据subscriber封装到typesBySubscriber中,第二个就是对黏性事件的处理。

事件的发送

在获取EventBus对象后,可以通过post方法来进行对事件的提交

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

首先从PostingThreadState对象中取出事件队列,然后将当前的事件插入使劲队列,然后将队列中的事件依次交给postSingleEvent处理,并移除该事件,然后跟踪postSingleEvent方法:

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

eventInheritance表示是否向上查找事件的父类,当其值为true时,则通过lookupAllEventTypes找到所有父类事件并存在List中,然后通过postSingleEventForEventType方法对事件进行逐一处理,跟踪postSingleEventType,首先取出该事件对应的Subscriptions(对象集合),

subscriptions = subscriptionsByEventType.get(eventClass);

然后遍历Subscriptions,将事件和对应的Subscription传递给postingState并调用postToSubscription方法对事件进行处理。

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

跟踪postToSubscription:

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

根据不同的线程模式做不同的处理:比如如果threadMode是MAIN,若提交事件的线程是主线程,则通过反射直接运行订阅的方法,不是主线程,则需要通过mainThreadPoster将我们的订阅事件添加到主线程队列中。

订阅者取消订阅

取消订阅需要调用unregister方法,如下所示。

public synchronized void unregister(Object subscriber) {
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);//1
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);//2
            }
            typesBySubscriber.remove(subscriber);//3
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

首先在1处根据订阅者找到事件类型集合。在注释3处将订阅者的从集合中移除。在注释2遍历subscribesTypes,并调用unsubscribeByEventType方法:通过eventType来得到对应的Subscription,并在for循环中判断如果Subscription的subscriber属性等于传进来的subscriber,则从Subscriptions中移除该Subscription。

你可能感兴趣的:(事件总线EventBus)