Android EventBus 3.0 用法及其原理详解

Android EventBus 3.0 用法及其原理详解

现在的项目中要用到应用程序内各组件间、组件与后台线程间的通信,2个方案可以实现这个功能,一个是利用回调。另一个是用EventBus。因为回调太繁琐,所以决定用EventBus。因为以前用过EventBus,所以直接去github看看有什么新功能,可一看,竟然3.0了,并且和2.0+的用法有很大的不同,所以就研究了下他的源码,记录下来,让大家参考参考,有什么不对的地方,欢迎大家指出。

我现在要介绍的是EventBus 3.0,你可以没有用过EventBus,因为我介绍的会很详细。

EventBus 3.0的使用

首先你要为你的app添加依赖库:
compile ‘org.greenrobot:eventbus:3.0.0’`

定义一个事件类型:里面的数据根据需求来,也可以是一个空的类。

`public class MainMessage {
    public String msg;
    public MainMessage(String msg) {
    this.msg = msg;
    }
}`

注册:注意,不要忘了在onDestroy里面的代码哦!

`@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //注册
    EventBus.getDefault().register(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    //反注册
    EventBus.getDefault().unregister(this);
}`

订阅:在注册了的页面中,声明处理事件的方法

`//主线程中执行
@Subscribe(threadMode = ThreadMode.MAIN,priority = 100)
public void onMainEventBus(MainMessage msg) {
    }
}`

1) ThreadMode总共四个:

NAIN UI主线程

BACKGROUND 后台线程

POSTING 和发布者处在同一个线程

ASYNC 异步线程

2) priority:事件的优先级类似广播的优先级,优先级越高优先获得消息.
3)Sticky事件的使用 :之前说的使用方法, 都是需要先注册(register), 再post,才能接受到事件; 如果你使用postSticky发送事件, 那么可以不需要先注册, 也能接受到事件。

首先,你可能需要声明一个方法

`   //注意,和之前的方法一样,只是多了一个 sticky = true 的属性.
    @Subscribe(threadMode = ThreadMode.MainThread, sticky = true)
    public void onEvent(MainMessage event){
    }`

其次, 你可以在没有register的情况下:(发送事件)

`EventBus.getDefault().postSticky(new MainMessage("With Sticky"));`

之后, 再注册,这样就可以收到刚刚发送的事件了:

`EventBus.getDefault().register(this);//注册之后,马上就能收到刚刚postSticky发送的事件`

发布:在任意地方,调用发送事件
EventBus.getDefault().post(new MainMessage(msg));

现在就ok了,如果你只是用的话就ok了,但是,如果不知道它的原理,我老感觉心里不舒服,用着不放心,接下来就介绍他的原理

首先,我们看看注册register()方法的实现

3.0的只提供了一个register()方法

` public void register(Object subscriber) {
    //首先获得订阅者的class对象
    Class<?> subscriberClass = subscriber.getClass();
    //通过subscriberMethodFinder来找到订阅者订阅了哪些事件.返回一个SubscriberMethod对象的List,SubscriberMethod
    //里包含了这个方法的Method对象,以及将来响应订阅是在哪个线程的ThreadMode,以及订阅的事件类型eventType,以及订阅的优
    //先级priority,以及是否接收粘性sticky事件的boolean值.
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            //订阅
            subscribe(subscriber, subscriberMethod);
        }
    }
}`

这里就是设计模式里我们常用的单例模式了,目的是为了保证getDefault()得到的都是同一个实例。如果不存在实例,就调用了EventBus的构造方法:

` private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

public EventBus() {
    this(DEFAULT_BUILDER);
}

EventBus(EventBusBuilder builder) {
    //key:订阅的事件,value:订阅这个事件的所有订阅者集合
    //private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    subscriptionsByEventType = new HashMap<>();
    //key:订阅者对象,value:这个订阅者订阅的事件集合
    //private final Map<Object, List<Class<?>>> typesBySubscriber;
    typesBySubscriber = new HashMap<>();
    //粘性事件 key:粘性事件的class对象, value:事件对象
    //private final Map<Class<?>, Object> stickyEvents;
    stickyEvents = new ConcurrentHashMap<>();
    //事件主线程处理
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
    //事件 Background 处理
    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;
}`

可以看出是通过初始化了一个EventBusBuilder()对象来分别初始化EventBus的一些配置,当我们在写一个需要自定义配置的框架的时候,这种实现方法非常普遍,将配置解耦出去,使我们的代码结构更清晰.

我把每行的代码都写了注释,可以看到register()方法很简洁,我们可以看出通过subscriberMethodFinder.findSubscriberMethods(subscriberClass)方法就能返回一个SubscriberMethod的对象,而SubscriberMethod里包含了所有我们需要的接下来执行subscribe()的信息.所以我们先去看看findSubscriberMethods()是怎么实现的,然后我们再去关注subscribe()。

SubscriberMethodFinder的实现

一句话来描述SubscriberMethodFinder类就是用来查找和缓存订阅者响应函数的信息的类。下面我们就来看findSubscriberMethods()到底是如何实现的:

`   List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    //先从METHOD_CACHE取看是否有缓存,key:保存订阅类的类名,value:保存类中订阅的方法数据,
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //是否忽略注解器生成的MyEventBusIndex类
    if (ignoreGeneratedIndex) {
        //利用反射来读取订阅类中的订阅方法信息
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        //从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
        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缓存
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}`

注释很详细我们就不在多说,由于篇幅原因我们就不在分析findUsingInfo()方法,其无非就是通过查找我们上面所说的MyEventBusIndex类中的信息,来转换成List从而获得订阅类的相关订阅函数的各种信息.有兴趣的可以自己研究看看,下面我们就来看findUsingReflection()方法是如何实现的:

`  private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
    //FindState 用来做订阅方法的校验和保存
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //通过反射来获得订阅方法信息
        findUsingReflectionInSingleClass(findState);
        //查找父类的订阅方法
        findState.moveToSuperclass();
    }
    //获取findState中的SubscriberMethod(也就是订阅方法List)并返回
    return getMethodsAndRelease(findState);
}`

这里通过FindState类来做订阅方法的校验和保存,并通过FIND_STATE_POOL静态数组来保存FindState对象,可以使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;
    }
    //遍历Method
    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();
                        //实例化SubscriberMethod对象并添加
                        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");
        }
    }
}`

到这里,我们订阅类的所有SubscriberMethod都已经被保存了,最后再通过getMethodsAndRelease()返回List至此,所有关于如何获得订阅类的订阅方法信息即:SubscriberMethod对象就已经完全分析完了.

post()方法原理分析

` public void post(Object event) {
    //得到当前线程的Posting状态.
    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;
        }
    }
}`

首先是通过currentPostingThreadState.get()方法来得到当前线程PostingThreadState的对象。
currentPostingThreadState的实现是一个包含了PostingThreadState的ThreadLocal对象,关于ThreadLocal
张涛的这篇文章解释的很好:ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,
而这段数据是不会与其他线程共享的。其内部原理是通过生成一个它包裹的泛型对象的数组,在不同的线程会有不同的数组索引值,通过这样就可以做到每个线程通过get() 方法获取的时候,取到的只能是自己线程所对应的数据。 所以这里取到的就是每个线程的PostingThreadState状态.接下来我们来看postSingleEvent()方法:

`private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //是否触发订阅了该事件(eventClass)的父类,以及接口的类的响应方法.
    if (eventInheritance) {
        //查找eventClass类所有的父类以及接口
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        //循环postSingleEventForEventType
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
            //只要右边有一个为true,subscriptionFound就为true
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        //post单个
        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) {
            //发送一个NoSubscriberEvent事件,如果我们需要处理这种状态,接收这个事件就可以了
            post(new NoSubscriberEvent(this, event));
        }
    }
}`

现在发现是在postSingleEventForEventType()方法里去进行事件的分发,代码如下:

` private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    //获取订阅了这个事件的Subscription列表.
    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;
}

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

总结上面的代码就是,首先从subscriptionsByEventType里获得所有订阅了这个事件的Subscription列表,然后在通过postToSubscription()方法来分发事件,在postToSubscription()通过不同的threadMode在不同的线程里invoke()订阅者的方法。

解除注册:unregister()方法分析

` public synchronized void unregister(Object subscriber) {
    //通过typesBySubscriber来取出这个subscriber订阅者订阅的事件类型,
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        //分别解除每个订阅了的事件类型
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        //从typesBySubscriber移除subscriber
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}`

然后是unsubscribeByEventType()方法的实现:

` private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //subscriptionsByEventType里拿出这个事件类型的订阅者列表.
    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--;
            }
        }
    }
}`

可以看出是从typesBySubscriber和subscriptions里分别移除订阅者以及相关信息.

现在EventBus3.0 的大概解析已经完了,我们知道了原理就可以放心大胆的用了

现在额外的说一下EventBus processor,因为现在还是测试版,所以不推荐使用,知道就好。

EventBus processor使用: EventBus提供了一个EventBusAnnotationProcessor注解处理器来在编译期通过读取@Subscribe()注解并解析,
处理其中所包含的信息,然后生成java类来保存所有订阅者关于订阅的信息,这样就比在运行时使用反射来获得这些订阅者的
信息速度要快.

具体使用:在build.gradle中添加如下配置:

`provided 'de.greenrobot:eventbus-annotation-processor:3.0.0-beta1'`

使用前后,我测了一下,我的项目的代码大概能相差8-9毫秒,这个时间对我来说不是很多,所以我项目中就没有用。

猜你喜欢

转载自blog.csdn.net/gemgaozhen/article/details/52837524