EventBus使用及源码解析之注册

EventBus 我们叫它事件总线,他能够将之前我们一些复杂的功能简单化,比如一个页面发送数据,其他多个页面也会收到消息,用它就比较方便和简单,并且包也不大。

实现方式:

   1.它是通过观察者模式实现事件的传递,通过注册事件(发布者),反注册事件(取消发布),及注解标记方法(订阅)来实现应用。

   2.内部实现通过获取订阅方法的注解获取配置信息并通过反射机制调用消费事件。

事件类型分为两种:

    1.普通事件:普通事件必须先注册,订阅方法,然后才能收到发送的消息,基本流程是:

     注册并订阅方法------>  post消息-------> 订阅方法收到消息(所有注册过,并订阅(添加Subscribe注解)的方法都会收到这条消息,这个与订阅时是否设置      sticky 为true或false无关。

    2.粘性事件:粘性事件可以不用先注册,当一条粘性消息发出时,我们来到下一个页面通过订阅(这时sticky必须为true),并注册了,这时就会收到先前发送的粘性事件,并且在我们收到粘性事件时如果不去调用remove 方法删除粘性消息,那么他会一直存在在消息集合中,当其他页面订阅注册时还会收到消息,并且是所有注册订阅过的方法都会收到,当然,这在之前当post一条消息时,所有注册过并订阅过的方法都会收到该消息,与发送是post()和stickPost()无关,粘性事件基本流程是:

    stickyPost消息------->订阅(加Subscribe关键字方法)并注册------->订阅方法收到粘性事件就消息。注意,如果这时有多个页面同时注册和订阅了事件,那么他们都会收到该消息。

基本使用:我直接贴代码了

    //注册事件
    @Override
    protected void onStart() {
        super.onStart();
        //注册事件
        EventBus.getDefault().register(this);
    }
    反注册事件
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册
        EventBus.getDefault().unregister(this);
    }
    //订阅事件,并且当前方法是在主线程中被调用的,sticky表示是否粘性事件
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = false)
    public void onEventTest(Object msg){
        Log.d(TAG, "onEvent: " + msg.toString());
        EventBus.getDefault().removeStickyEvent(msg);
    }

发送事件
EventBus.getDefault().post("普通事件");

EventBus.getDefault().postSticky("粘性事件");

特点:

1.当一个页面已经注册并且订阅了事件,这时其他页面,无论发送的是哪种发送方式,该页面订阅方法都会收到消息。

2.当一个页面A订阅和注册了事件,先发送一条粘性事件,然后跳转到页面B但是它通过postStick发送事件,页面B 注册了并且订阅了事件,且sticky=trur;这时A会先收到它发送的消息,然后B页面也会收到消息。从A发送粘性事件到B 收到粘性事件,我们暂且叫做粘性事件的一个回路。这也基本是粘性事件的最多使用点。

使用起来很多简单,下面我们看源码:

事件的注册:

EventBus.getDefault().register(this);

getDefault 通过双重锁单例获取了一个EventBus实例,这里做了一些集合等的初始化动作。

    public void register(Object subscriber) {
       //获取当前类的class对象
        Class subscriberClass = subscriber.getClass();
       //获取当前类中所有的订阅方法封装类SubscriberMethod 集合
        List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //循环调用订阅
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

SubscriberMethod 类是订阅方法的一个封装体,

1.保存了订阅函数的方法对象method

2.保存了当前订阅方法的注解信息,例如线程,是否粘性,优先级

3.保存了当前订阅类的class对象

findSubscriberMethods 方法实现

METHOD_CACHE是一个map缓存器

private static final Map, List> METHOD_CACHE = new ConcurrentHashMap<>();
 List findSubscriberMethods(Class subscriberClass) {
        //通过clas 对像获取方法封装集合
        List 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;
        }
    }

findUsingInfo 方法主要用于实现获取方法封装类的集合。

 private List findUsingInfo(Class subscriberClass) {
        //初始化对象池
        FindState findState = prepareFindState();
        //设置订阅类class对象
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //这里获取到的值是空,通过上一步可知
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
               //获取SubscriberMethod 数组,当前类中
                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();
        }
         //将findState中SubscriberMethod 集合取出
        return getMethodsAndRelease(findState);
    }

FindState 类也是一个方法信息类,并且创建了一个类工具池,大小是4个,部分类内容

static class FindState {
        这个集合就是上边我们要的返回的方法封装集合
        final List subscriberMethods = new ArrayList<>();
        // 方法参数class 为key 值为方法函数   的map
        final Map anyMethodByEventType = new HashMap<>();
        // key 函数名和注册类名拼接字串 value 订阅函数methclass  的map
        final Map subscriberClassByMethodKey = new HashMap<>();
        // 这个是用于拼接subscriberClassByMethodKey 的key 的StringBuilder,这里没有牵扯对多线程,所以用效率较高的StringBuilder
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class subscriberClass;
        Class clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;

        void initForSubscriber(Class subscriberClass) {
            this.subscriberClass = clazz = subscriberClass;
            skipSuperClasses = false;
            subscriberInfo = null;
        }
       // 回收内存,用于复用
        void recycle() {
            subscriberMethods.clear();
            anyMethodByEventType.clear();
            subscriberClassByMethodKey.clear();
            methodKeyBuilder.setLength(0);
            subscriberClass = null;
            clazz = null;
            skipSuperClasses = false;
            subscriberInfo = null;
        }
findUsingReflectionInSingleClass 方法组装实现FindState类,其中有用到注解相关知识,如果不了解可以参考如何自定义一个注解并获取注解
private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            //反射获取注册类中所有方法返回methods 数组
           //表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            try {
                //反射获取注册类中所有方法返回methods 数组
                //返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法。
                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) {
                //获取该方法的参数类型,返回一个clase数组
                Class[] parameterTypes = method.getParameterTypes();
                //参数至少要有一个否则会报异常
                if (parameterTypes.length == 1) {
                   //获取注解 订阅信息 Subscribe类
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                           //线程枚举类型,决定了调用函数在那个线程工作
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            //将符合条件的函数添加进findState中的subscriberMethods集合
                            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");
            }
        }
    }
getMethodsAndRelease 方法主要是获取 FindState 中 List
private List getMethodsAndRelease(FindState findState) {
        //获取订阅方法封装类集合
        List subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        //回收findState
        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;
    }

到此List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

执行完成了,我们拿到了subscriberMethods 也就是getMethodsAndRelease方法返回的集合。一般情况下集合只有一个方法,因为多数情况我们在一个activity/Fragment 中只订阅一个方法。

然后回到register 类

public void register(Object subscriber) {
    Class subscriberClass = subscriber.getClass();
    List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
       //遍历当前类,调用subscribe 方法订阅
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

在看subscribe前先了解些SubscriberMethod 构造函数参数

public SubscriberMethod(Method method, Class eventType, ThreadMode threadMode, int priority, boolean sticky) {
    //当前函数
    this.method = method;
    // 当前函数 运行线程
    this.threadMode = threadMode;
    //当前函数的参数类型
    this.eventType = eventType;
    // 优先级
    this.priority = priority;
    //是否粘性事件
    this.sticky = sticky;
}
 // Must be called in synchronized block
    // subscriber 就是注册类对象, subscriberMethod 是注册类中一个订阅方法封装类
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //获取订阅函数参数类型
        Class eventType = subscriberMethod.eventType;
        //Subscription 又对 就是注册类对象 和注册类中一个订阅方法封装类 进行封装,并且重写了equals 和 hashCode方法,
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //subscriptionsByEventType 用于存放订阅方法封装类的map key 是当前函数的参数类型,value是Subscription集合 ,key用于将相同函数参数类型的subscriptions 放到集合中
        CopyOnWriteArrayList 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();
        //将当前subscriptions 对像放在集合的最后一位,例如现在集合中有两条数据size=2,那么就将新的放在下标为2处。可见subscriptionsByEventType 设计的比较巧妙。
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        List> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        //typesBySubscriber key为订阅类实例,value 是 List>  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).
               //遍历粘性事件map   stickyEvents
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, 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);
            }
        }
    }

newSubscription 是上边我们说订阅函数等的封装类,stickyEvent 是要发送的事件消息

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

invokeSubscriber 是执行到的最终方法,调用了invoke 反射方法,调用了订阅类并将参数传进去,这时我们订阅方法就会执行,并且是执行在我们设定的线程中的。如果对反射不了解可以参考java反射invoke方法的使用

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

 总结:这里可以看到我们在注册事件的过程中主要做了两件事情,1.将订阅的方法相关信息进行保存的过程。2.如果是粘性事件,同时查询粘性map ,将map中的所有粘性消息通过订阅方法发出,这就是整个消息注册的过程。

 

 

 

 

 

你可能感兴趣的:(个人笔记)