EventBus详解

1 EventBus 简介

简介

EventBus是一种用于Android的事件发布-订阅总线,由GreenRobot开发,它简化了应用程序内各个组件之间进行通信的复杂度,尤其是碎片之间进行通信的问题,可以避免由于使用广播通信而带来的诸多不便。这里的事件可以理解为消息,传统的事件传递方式包括:Intent、Handler、BroadCastReceiver、Interface 回调,相比之下 EventBus 的优点是代码简洁,使用简单,并将事件发布和订阅充分解耦。可简化 Activities, Fragments, Threads, Services 等组件间的消息传递,可替代 Intent、
Handler、BroadCast、接口等传统方案,更快,代码更小,50K 左右的 jar 包,代码更优雅,彻底解耦。
Github

角色

  • 事件(Event):又可称为消息,本文中统一用事件表示。其实就是一个对象,可以是任意类型。事件类型(EventType)指事件所属的Class。 事件分为一般事件和 Sticky 事件,相对于一般事件,Sticky 事件不同之处在于,当事件发布后,再有订阅者开始订阅该类型事件,依然能收到该类型事件最近一个 Sticky 事件。
  • 订阅者(Subscriber):订阅某种事件类型的对象。当有发布者发布这类事件后,EventBus会执行订阅者的 onEvent 函数,这个函数叫事件响应函数。订阅者通过 register 接口订阅某个事件类型,unregister 接口退订。订阅者存在优先级,优先级高的订阅者可以取消事件继续向优先级低的订阅者分发,默认所有订阅者优先级都为 0。在EventBus 3.0之前我们必须定义以onEvent开头的那几个方法,分别是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync;而在3.0之后事件处理的方法名可以随意取,不过需要加上注解@subscribe,并且指定线程模型,默认是POSTING。

关系图

  1. EventBus 、订阅者、发布者关系图
    EventBus 负责存储订阅者、事件相关信息,订阅者和发布者都只和 EventBus 关联。
    请添加图片描述

  2. 事件相应流程
    订阅者首先调用 EventBus 的 register 接口订阅某种类型的事件,当发布者通过 post接口发布该类型的事件时,EventBus 执行调用者的事件响应函数
    请添加图片描述

四种线程模型

  • POSTING:默认,表示事件处理函数的线程跟发布事件的线程在同一个线程。
  • MAIN:表示事件处理函数的线程在主线程(UI)线程,因此在这里不能进行耗时操作。
  • ASYNC:表示无论事件发布的线程是哪一个,事件处理函数始终会新建一个子线程运行,同样不能进行UI操作,可以异步并发处理。
  • BACKGROUND:表示事件处理函数的线程在后台线程,因此不能进行UI操作。如果发布事件的线程是主线程(UI线程),那 么事件处理函数将会开启一个后台线程,如果果发布事件的线程是在后台线程,那么事件处理函数就使用该线程,不能并发处理。

2.EventBus使用步骤

添加依赖

implementation("org.greenrobot:eventbus:3.3.1")

注册

通常注册、解注册、接收消息都在一起(同一个页面中),发送在另外的地方。
避免重复注册,重复注册可能导致存在多个此类对象可能导致重复多次的接收

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

解注册

在退出页面时解注册 比如

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

创建消息类

比如 消息类 Msg

public class Msg {
    private String msg;

    public Msg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "Msg{" +
                "msg='" + msg + '\'' +
                '}';
    }
}

发送消息

  EventBus.getDefault().post(new Msg("EventBus  发送消息"));

接收消息

通常注册、解注册、接收消息都在一起,发送在另外的地方。

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Msg msg) {
        Log.i("TAG", "MainActivity 页面 msg:" + msg.getMsg().toString());
    }

粘性事件

指发送了该事件之后再订阅者依然能够接收到的事件。使用黏性事件的时候有两个地方需要做些修改。一个是订阅事件的地方,这里我们在先打开的Activity中注册监听黏性事件;另一个是接受接收事件的方法需要修改。

发送消息 使用postStick()

EventBus.getDefault().postSticky(new Msg("EventBus  发送消息"));

接受消息

sticky是一个boolean型的参数,默认值是false,表示不启用sticky特性。

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onGetStickyEvent(Msg msg) {
        Log.i("TAG", "MainActivity 页面 粘性事件 msg:" + msg.getMsg().toString());
}

3 EventBus做通信优点

1.简化了组件间交流的方式
2.对事件通信双方进行解耦
3.可以灵活方便的指定工作线程,通过ThreadMode
4.速度快,性能好
5.库比较小,不占内存
6.使用这个库的app多,有权威性
7.功能多,使用方便

4 源码

getDefault()

    /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        EventBus instance = defaultInstance;
        if (instance == null) {
            synchronized (EventBus.class) {
                instance = EventBus.defaultInstance;
                if (instance == null) {
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
    }

EventBus 类采用了Double Check 的单例类。
接下类看下它的构造函数。它的无参构造函数调用的是EventBus(EventBusBuilder)的有参构造函数,传入的参数是DEFAULT_BUILDER,而 DEFAULT_BUILDER 则是一个调用了 EventBusBuilder默认构造器的对象。可以看出,这里用到了 Builder 模式来支持用EventBusBuilder 进行一些配置。

EventBus(EventBusBuilder builder)主要进行的是一些容器的初始化以及将一些配置参数从 Builder中取出。

    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

    /**
     * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
     * central bus, consider {@link #getDefault()}.
     */
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
        logger = builder.getLogger();
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadSupport = builder.getMainThreadSupport();
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
        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;
    }

register()

    /**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        if (AndroidDependenciesDetector.isAndroidSDKAvailable() && !AndroidDependenciesDetector.areAndroidComponentsAvailable()) {
            // Crash if the user (developer) has not imported the Android compatibility library.
            throw new RuntimeException("It looks like you are using EventBus on Android, " +
                    "make sure to add the \"eventbus\" Android library to your dependencies.");
        }

        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

register 传入的 register 是一个 Object 类型(任意类型都可以通过EventBus的register)。首先是if判断,它获取到了 subscriber 的类型信息,然后将其传递给了 subscriberMethodFinder 的 findSubscriberMethods() 方法。通过名称可以很容易看出,SubscriberMethodFinder 类是一个专门用来搜索查询subscriber 中含有 @Subscribe 注解的方法的类。这里进行的操作就是将所有被 @Subscribe 标记的方法都加入到 List 中;加锁保证了线程安全。

findSubscriberMethods方法

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

ignoreGeneratedIndex 为true 时调用的是findUsingReflection(subscriberClass);通过反射来搜索方法;ignoreGeneratedIndex 为false 时,findUsingInfo(subscriberClass)进行搜索,

findUsingReflection方法

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

搜索到的结果通过FindState 来存储。FindState是SubscriberMethodFinder的内部类。
在while 循环,它先执行了 findUsingReflectionInSingleClass 方法通过反射找到所有被 @Subscribe 标注的方法,再通过 moveToSuperclass 向这个类的父类进行搜索查询

findUsingReflectionInSingleClass方法

    
    private static final int MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
    
    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");
            }
        }
    }

getDeclaredMethods、getMethods都是用来获取Method列表。获取到Method列表后进行for循环校验(两次校验),检验是否被Subscribe修饰的方法是否是public、non-static、non-abstract,non-protected;通过checkAdd进行校验。

checkAdd方法、checkAddWithMethodSignature方法

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

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

moveToSuperclass 方法

该方法向其父类进行查询

    void moveToSuperclass() {
        if (skipSuperClasses) {
            clazz = null;
        } else {
            clazz = clazz.getSuperclass();
            String clazzName = clazz.getName();
            // Skip system classes, this degrades performance.
            // Also we might avoid some ClassNotFoundException (see FAQ for background).
            if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") ||
                    clazzName.startsWith("android.") || clazzName.startsWith("androidx.")) {
                clazz = null;
            }
        }
    }

findUsingInfo方法

通过 getSubscriberInfo(findState)获取到了由 Builder 过程传入的SubscriberInfoIndex,从中获取需要的信息。当其值为 null 时,再使用反射的方式进行搜索查询

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

subscribe 方法 订阅流程

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
       // 检查同样的方法是否已经被注册过,没有则将其放入 Map 中,否则抛出异常。
        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);
            }
        }
	
	//将其按照优先级放入以该 Event 为参数的方法列表中。
        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;
            }
        }

		//以该 subscriber 为 key,以它内部所有被 @Subscribe 标记的方法的列表为 value 的 Map typesBySubscriber 中
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

		//对stick事件的处理。主要逻辑是:首先判断了 Event 是否子 Event,若是一个子 Event 则找到其父 Event 作为参数 Event,否则将其作为参   数 Event,然后在判 null 的情况下调用 postToSubscription 方法来执行这个方法
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
				// 必须考虑eventType的所有子类的现有粘性事件.
                // 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>).
                //(例如,存储超类的子类的附加映射: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);
            }
        }
    }

Subcription是一个将 Subcriber 及 SubcriberMethod 进行包装的类.

post方法

    /** Posts the given event to the event bus. */
    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        // event 插入 eventQueue 中
        eventQueue.add(event);

        if (!postingState.isPosting) {//避免每次post方法都会去调用整个队列。
            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 对象,它的类型是PostingThreadState,这个类的主要用途是记录事件的发布者的线程信息。currentPostingThreadState 维护一个eventQueue,

首先,将 Event 插入了 eventQueue 中,之后将 isMainThread 等信息进行填充。同时将 postingState 的 isPosting 置为了 true,使得事件 post 的过程中当前线程的其他 post 事件无法被相应,当 post 过程结束后,再将其置为true。

while 循环中遍历队列中所有event,调用 postSingleEvent(eventQueue.remove(0), postingState);

    /** For ThreadLocal, much faster to set (and get multiple values). */
    final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<>();
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }

currentPostingThreadState 的创建

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

通过ThreadLocal来保存currentPostingThreadState。
ThreadLocal 作用:是一个用于创建线程局部变量的类。它创建的变量只能被当前线程访问,其他线程则无法访问和修改。(比如Looper 的创建)

postSingleEvent、 postSingleEventForEventType、 postToSubscription

通过 postSingleEventForEventType 来进行搜寻对应Subscription,如果 Event 是子 Event,则获取它的所有父 Event 列表,再遍历列表进行搜索查询。否则直接调用 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) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
//如果在没有找到对应的 subscription,创建一个NoSubscriberEvent 再调用 post 请求。这样无论 event 是否有 Subscriber,它都会进行一次检测。
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

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

postSingleEventForEventType方法根据 event 找到了所有对应的 Subscription,然后遍历 subscription列表调用 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 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);
        }
    }

postToSubscription方法 是对订阅者线程进行判断。采用不同的 Poster 进行入队操作,通过队列的方式进行一一处理。对某些特殊情况则直接调用invokeSubscriber(subscription, event) 进行处理。在 Poster 内部调用的是 invokeSubscriber(PendingPost)

invokeSubscriber方法

通过反射来对方法进行调用。


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

/**
 * Invokes the subscriber if the subscriptions is still active. Skipping subscriptions prevents race conditions
 * between {@link #unregister(Object)} and event delivery. Otherwise the event might be delivered after the
 * subscriber unregistered. This is particularly important for main thread delivery and registrations bound to the
 * live cycle of an Activity or Fragment.
 */
void invokeSubscriber(PendingPost pendingPost) {
    Object event = pendingPost.event;
    Subscription subscription = pendingPost.subscription;
    PendingPost.releasePendingPost(pendingPost);
    if (subscription.active) {
        invokeSubscriber(subscription, event);
    }
}

invokeSubscriber(pendingPost)在内部判断了 Subscription 的 active 状态,如果为 active(true),再调用 invokeSubscriber(subscription, event) 方法对 Method 进行执行。这个 active 状态可以使得 unregister 的unsubscribeByEventType方法中的对应 Method 不再被执行( subscription.active = false;)

    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

postSticky方法

 private final Map<Class<?>, Object> stickyEvents;
    /**
     * Posts the given event to the event bus and holds on to the event (because it is sticky). The most recent sticky
     * event of an event's type is kept in memory for future access by subscribers using {@link Subscribe#sticky()}.
     */
    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);
    }

将event 加入到stickyEvents列表,再执行post方法

unregister方法

    /** Unregisters the given subscriber from all event classes. */
    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 {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

先判断了这个 Event 是否还未注册,若已注册则遍历执行 unsubscribeByEventType(subscriber, eventType)方法取消订阅,同时执行 typesBySubscriber.remove(subscriber);把Subcriber 所对应的信息从 typesBySubscriber 这个 Map 中移除。

unsubscribeByEventType方法

    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

将 subscriptionsByEventType 中与 EventType 对应的Subscription 列表取出,遍历并将该 subscriber对应的 Subscription 的 active标记为 false 并删除。

5 总结

EventBus是在一个单例内部维持着一个 map 对象存储了一堆的方法;post根据参数去查找方法,进行反射调用(register会把当前类中匹配的方法,存入一个 map, post根据实参去 map 查找进行反射调用)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EventBus是一个开源的发布/订阅事件总线库,它简化了不同组件之间的通信,避免了紧密耦合的代码。它使用了观察者模式,让不同的组件能够在没有直接关联的情况下相互通信。下面是EventBusAndroid中的使用详解。 1.导入EventBus库 在build.gradle文件中添加以下代码: ``` dependencies { implementation 'org.greenrobot:eventbus:3.2.0' } ``` 2.定义事件类 定义一个事件类,用于传递数据。 ```java public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } } ``` 3.注册EventBus 在需要接收事件的组件中注册EventBus。 ```java @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } ``` 4.注销EventBus 在不需要接收事件的组件中注销EventBus。 ```java @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } ``` 5.发布事件 在发送事件的组件中发布事件。 ```java EventBus.getDefault().post(new MessageEvent("Hello EventBus!")); ``` 6.订阅事件 在接收事件的组件中订阅事件。 ```java @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { String message = event.message; // 处理事件 } ``` 7.指定线程模式 EventBus支持在不同的线程中处理事件,可以通过@Subscribe注解的threadMode参数指定线程模式。 ```java @Subscribe(threadMode = ThreadMode.MAIN) // 主线程 public void onMessageEvent(MessageEvent event) { String message = event.message; // 处理事件 } @Subscribe(threadMode = ThreadMode.BACKGROUND) // 后台线程 public void onMessageEvent(MessageEvent event) { String message = event.message; // 处理事件 } @Subscribe(threadMode = ThreadMode.ASYNC) // 异步线程 public void onMessageEvent(MessageEvent event) { String message = event.message; // 处理事件 } ``` EventBus的使用非常简单,但是需要注意以下几点: - 订阅方法必须使用@Subscribe注解,并且方法必须是public、void类型。 - 发布事件和接收事件的参数类型必须一致。 - 在注册EventBus时,不要忘记在onStop()方法中注销EventBus,否则可能会引起内存泄漏。 - EventBus默认在主线程中处理事件,如果事件处理需要耗时操作,可以使用不同的线程模式。 - EventBus不支持跨进程通信,只能在同一进程中的组件之间进行通信。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值