Android EventBus 初识

366 阅读10分钟
带着问题进入今天的话题
  1. EventBus的作用和优点?
  2. EventBus是怎么实现组件之间的通信的?

EventBus github地址:github.com/greenrobot/…

EventBus简单使用:
1,添加依赖

implementation 'org.greenrobot:eventbus:3.2.0'

2,注册订阅

EventBus.getDefault().register(this);
  
3 实现订阅方法,从3.0开始使用Subscribe注解替代onEvent方法,通过传入的参数类型来区分事件调用方法

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}

4 取消注册

EventBus.getDefault().unregister(this);

完整源码演示:

public class MainActivity extends AppCompatActivity {

    private TextView tvMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvMsg = findViewById(R.id.tv_msg);
        //注册订阅
        EventBus.getDefault().register(this);
    }

    // 实现订阅方法,从3.0开始使用Subscribe注解替代onEvent方法
    // 通过传入的参数类型来区分事件调用方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String msg) {
        tvMsg.setText("onMessageEvent1:" + msg);
    }

    @Subscribe
    public void onMessageEvent(Event event) {
        tvMsg.setText("onMessageEvent2:" + event.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        EventBus.getDefault().unregister(this);
    }
可以在任意位置送消息
EventBus.getDefault().post("第一次使用EventBus,忘大佬们多多关注一下!");
设计思路

EventBus是Android中一款发布-订阅事件总线框架,将事件的接收者和发送者分开,简化了组件之间的通信,使用简单灵活,且执行效率高!

Publiser(发布者)通过post()发送事件到EventBus,而EventBus作为一个分发器或者是调度器,将事件通知到各大Subcriber(订阅者)。

直接拷贝被人的图了懒得自己去搞 image.png

源码分析:

EventBus.getDefault().register(this);

//getDefault()是一个单例方法,保证当前只有一个EventBus实例:
public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

可以看到register()方法主要分为查找和注册两部分,首先来看查找的过程,从findSubscriberMethods()开始

public void register(Object subscriber) {
        // 获取当前要注册类的Class对象
        Class<?> subscriberClass = subscriber.getClass();
        // 根据Class查找当前类中订阅了事件的方法集合(使用了Subscribe注解、有public修饰符、一个参数的方法)
        // SubscriberMethod类主要封装了符合条件的方法的相关信息(Method对象、线程模式、事件类型、优先级)
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

        synchronized (this) {
            // 循环遍历订阅了事件的方法集合,以完成注册
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

findSubscriberMethods()先从缓存中查找,如果找到则直接返回,没有findUsingInfo()方法会被调用。

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // METHOD_CACHE是一个ConcurrentHashMap,保存了subscriberClass和对应SubscriberMethod的集合,以提高注册效率,防止重复查找。
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        // 由于使用了默认的EventBusBuilder,默认为false,是否忽略注解生成器
        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 {
            // 保存查找到的List<SucribeMethod>集合到缓存中去
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

findUsingInfo() 方法循环遍历该类,父类,父父类........ 调用findUsingReflectionInSingleClass() 查找订阅事件的方法

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();// FindState保存了一些查找到的数据和状态
        findState.initForSubscriber(subscriberClass);
        // 初始状态下findState.clazz就是subscriberClass
        while (findState.clazz != null) {
            findState.subscriberInfo = getSubscriberInfo(findState);
            // 获取订阅者信息,没有配置EventBusIndex 返回null
            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.clazz为subscriberClass的父类Class,即需要遍历父类
            findState.moveToSuperclass();
        }
        // 查找到的方法保存在了FindState实例的subscriberMethods集合中。
        // 使用subscriberMethods构建一个新的List<SubscriberMethod>
        // 释放掉findState
        return getMethodsAndRelease(findState);
    }

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();
        } 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(); // 获得方法的修饰符
             //从这里看出必须是public方法才会被订阅 
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                         Class<?>[] parameterTypes = method.getParameterTypes();// 获得当前方法所有参数的类型
                //参数数量为1的才会被订阅         
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                     if (subscribeAnnotation != null) {
                        // 得到该参数的类型
                        Class<?> eventType = parameterTypes[0];
                        // checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回true
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            // 创建一个SubscriberMethod对象,并添加到subscriberMethods集合
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {...}// 抛出异常
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {...}// 抛出异常
        }
    }

到此register()方法中findSubscriberMethods()流程就分析完了,我们已经找到了当前注册类及其父类中订阅事件的方法的集合。接下来分析具体的注册流程,即register()中的subscribe()方法:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 得到当前订阅了事件的方法的参数类型
        Class<?> eventType = subscriberMethod.eventType; 
        // Subscription类保存了要注册的类对象以及当前的subscriberMethod
        Subscription newSubscription = newSubscription(subscriber,subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions=subscriptionsByEventType.get(eventType);
         if (subscriptions == null) {
            // 如果不存在,则创建一个subscriptions,并保存到subscriptionsByEventType
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }
        // 添加上边创建的newSubscription对象到subscriptions中
        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); 
        // 不存在则创建一个subscribedEvents,并保存到typesBySubscriber
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        // 保存当前订阅了事件的方法的参数类型
        subscribedEvents.add(eventType);
        // 粘性事件相关的
        if (subscriberMethod.sticky) {
            ...
        }
    }

subscribe()方法主要是得到了subscriptionsByEventType、typesBySubscriber这两个 HashMap。 发送事件的时候要用到subscriptionsByEventType,完成事件的处理。当取消注册的时候要用到typesBySubscriber、subscriptionsByEventType,完成相关资源的释放。

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;

subscriptionsByEventType里面到底存放的什么? 举个栗子吧。       
CopyOnWriteArrayList<Subscription> listC;
listC.add(new Subscription(UserA, UserAMethod))
listC.add(new Subscription(UserA, UserAMethod2))
listC.add(new Subscription(UserB, UserBMethod))
subscriptionsByEventType.put(String.class,listC)

UserAMethod,UserAMethod2就是订阅在UserA类中的参数类型是String的方法
UserBMethod 是订阅在UserB类中的参数类型是String的方法

//就是下面这玩意
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(String msg) {
    tvMsg.setText("onMessageEvent1:" + msg);
}

除了String类型可能还会有很多类型:
subscriptionsByEventType.put(Interger.class,listx)
subscriptionsByEventType.put(MyLoginEvent.class,listxx)
subscriptionsByEventType.put(MyLogin2Event.class,listxxx)等等

什么要这么存放呢?EventBus作为一个分发器或者是调度器,
将事件通知到各大Subcriber(订阅者)就是通过参数类型判断的, 
分发器会通知所有参数类型相同的订阅方法 设计如此而已!

typesBySubscriber这里有存放的什么呢?
UserA,UserB类中都有订阅参数类型为String的方法 
List<Class<?>> list
list.add(UserA.class)
list.add(UserB.class)
typesBySubscriber.put(Stirng.class,list)
typesBySubscriber有什么用呢?
取消注册的时候要用到typesBySubscriber、subscriptionsByEventType

知晓了subscriptionsByEventType、typesBySubscriber这两个map存放的什么后 post()方法也就好理解了

EventBus.getDefault().post("我是一个栗子")

public void post(Object event) {
        // currentPostingThreadState是一个PostingThreadState类型的ThreadLocal
        // PostingThreadState类保存了事件队列和线程模式等信息(可以理解为执行post的辅助类)
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        // 将要发送的事件添加到事件队列
        eventQueue.add(event);
        // isPosting默认为false
        if (!postingState.isPosting) {
            // 是否为主线程
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                // 遍历事件队列
                while (!eventQueue.isEmpty()) {
                    // 发送单个事件
                    // eventQueue.remove(0),从事件队列移除事件
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

post()方法主要做了 先将发送的事件保存的事件队列,然后通过循环出队列,将事件交给postSingleEvent()方法处理。我们直接看postSingleEvent()方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();// 获取这个事件类型的class对象
        boolean subscriptionFound = false;
        // eventInheritance默认为true,表示是否向上查找事件的父类
        if (eventInheritance) {
            // 查找当前事件类型的Class,连同当前事件类型的class对象保存到集合
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            // 遍历事件类型class集合,继续处理事件
            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);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

postSingleEvent()方法中,根据eventInheritance属性,决定是否向上遍历事件的父类型,然后用postSingleEventForEventType()方法进一步处理事件。不太好理解的话 我们只直接进入postSingleEventForEventType()方法:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
                   subscriptions = subscriptionsByEventType.get(eventClass);// 获取事件类型对应的Subscription集合
        }
        // 如果已订阅了对应类型的事件
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;// 记录事件
                       postingState.subscription = 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;
    }

上面register()存储的subscriptionsByEventType map就是在postSingleEventForEventType()方法用到的。遍历发送的事件类型对应的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 {
                     // 如果是在子线程发送事件,则将事件入队列,通过Handler切换到主线程执行处理事件
                    // mainThreadPoster 不为空
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            // 无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
            // mainThreadPoster 不为空
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    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()内部会根据订阅事件方法的线程模式,间接或直接的以发送的事件为参数,通过反射执行订阅事件的方法。

可以看到,postToSubscription()方法就是根据订阅事件方法的线程模式、以及发送事件的线程来判断如何处理事件,至于处理方式主要有两种: 一种是在相应线程直接通过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);
        }
    }

另外一种是先将事件入队列(其实底层是一个List),然后做进一步处理,我们以mainThreadPoster.enqueue(subscription, event)为例简单的分析下,其中mainThreadPoster是HandlerPoster类的一个实例,来看该类的主要实现

public class HandlerPoster extends Handler implements Poster {
    private final PendingPostQueue queue;
    private boolean handlerActive;
    ......
    public void enqueue(Subscription subscription, Object event) {
        // 用subscription和event封装一个PendingPost对象
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            // 入队列
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                // 发送开始处理事件的消息,handleMessage()方法将被执行,完成从子线程到主线程的切换
                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();
                ......
                // 进一步处理pendingPost
                eventBus.invokeSubscriber(pendingPost);
                ......
            }
        } finally {
            handlerActive = rescheduled;
        }
    }
}

.....
void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        // 释放pendingPost引用的资源
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            // 用反射来执行订阅事件的方法
            invokeSubscriber(subscription, event);
        }
    }
....

到此 EventBus核心源码基本就结束了,最后简单看下EventBus取消注册

EventBus.getDefault().unregister(this);

public synchronized void unregister(Object subscriber) {
        // 得到当前注册类对象 对应的 订阅事件方法的参数类型 的集合
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            // 遍历参数类型集合,释放之前缓存的当前类中的Subscription
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            // 删除以subscriber为key的键值对
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }
 
 private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        // 得到当前参数类型对应的Subscription集合
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            // 遍历Subscription集合
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                // 如果当前subscription对象对应的注册类对象 和 要取消注册的注册类对象相同,则删除当前subscription对象
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }
    

在unregister()方法中,释放了typesBySubscriber、subscriptionsByEventType中缓存的资源。

EventBus简单核心代码看完了,加深了我对注解跟反射的运用,map跟list运用去存储对象,参数类型。