EventBus源码解析

事件总线

  • 为了简化并且高质量地在Activity、Fragment、Thread和Service间通信,同时解决组件之间高耦合的同时仍然能高效地通信,事件总线设计出现了。
  • 提到事件总线我们会想到Eventbus和otto,这里讲解他们的用法和原理。

7.1 解析EventBus

  • EventBus是一款针对Android优化的发布-订阅事件总线。简化了应用程序内各组件间、组件与后台进程间的通信。
  • 将发送者和接收者进行解耦。
    在这里插入图片描述

7.1.1 使用EventBus

1. 三要素

  • 先了解EventBus的三要素以及4种ThreadMode
    请添加图片描述
    在这里插入图片描述

2. 线程模型

请添加图片描述

3. EventBus的基本用法

在这里插入图片描述

  • 消息处理的方式可以随便取名,但是需要加一个注解@Subscribe,并且要指定线程模型。
    在这里插入图片描述

4. EventBus使用案例

  • 这里使用项目中的一个简单案例
  1. 导入依赖
implementation 'org.greenrobot:eventbus:3.1.1'
  1. 定义消息事件类
package eventbus;


//事件
//挑战详细介绍界面的Back返回按键
public class EventChallenge_CardActivity_Back {
    Boolean click_back;
    public EventChallenge_CardActivity_Back(Boolean click_back){
        this.click_back = click_back;
    }

    public Boolean getClick_back() {
        return click_back;
    }

    public void setClick_back(Boolean click_back) {
        this.click_back = click_back;
    }
}
  1. 注册和取消订阅事件
  • 在onCreate方法中
//初始化EventBus
EventBus.getDefault().register(this);
  • 在onDestroy中
EventBus.getDefault().unregister(this);
  1. 事件订阅者处理事件
//5.EventBus订阅者事件
//此事件对应的是卡片详细介绍界面点击back,退出当前卡片介绍界面
@Subscribe(threadMode = ThreadMode.POSTING , sticky = true)
public void fromChallengeCardActivityBack(EventChallenge_CardActivity_Back back){
    Log.d("Ning","fromChallengeCardActivityBack");
    //如果为true,表示点击了back
    if(back.getClick_back()){
        replaceFragment((Fragment) ARouter.getInstance().build("/challenge/ChallengeFragment").navigation());
    }
}
  1. 事件发布者发布消息
...
//1.两个相关的点击事件
@Override
public void onClick(View v) {
    if (v.getId() == R.id.challenge_firstCard_back) {
        //点击back按键继续给main模块发送黏性事件,告诉它我要切换回之前的Fragment
        EventBus.getDefault().postSticky(new EventChallenge_CardActivity_Back(true));
        ....
  • 补充
  • 这是书中的测试样例
    在这里插入图片描述

5. EventBus的黏性事件

  • 上面的事件就是黏性事件。一般要求先有订阅者,才能接收到事件。
  • 黏性事件可以在发送事件之后再订阅该事件也能接收到该事件。

7.1.2 源码解析EventBus

  • 来了解EventBus的源码

1. EventBus的构造方法

  • 当我们使用EventBus的时候,首先会调用EventBus.getDefault()来获取EventBus实例,现在查看getDefault()方法做了些什么。
  • 这是一个单例模式,采用了双重检查模式(DCL)。
public static EventBus getDefault() {
    if (defaultInstance == null) {
        Class var0 = EventBus.class;
        synchronized(EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }

    return defaultInstance;
}
  • 来看EventBus的构造方法
  • 这里的DEFAULT_BUILDER是默认的EventBusBuilder,用来构造EventBus。
public EventBus() {
    this(DEFAULT_BUILDER);
}
  • this调用了EventBus的另外一个构造方法
  • 我们可以通过构造一个EventBusBuilder来对EventBus进行配置,这里采用了建造者模式。
EventBus(EventBusBuilder builder) {
    //通过传进来的EventBusBuilder来对EventBus的内部变量进行配置
    this.currentPostingThreadState = new ThreadLocal<EventBus.PostingThreadState>() {
        protected EventBus.PostingThreadState initialValue() {
            return new EventBus.PostingThreadState();
        }
    };
    this.logger = builder.getLogger();
    this.subscriptionsByEventType = new HashMap();
    this.typesBySubscriber = new HashMap();
    this.stickyEvents = new ConcurrentHashMap();
    this.mainThreadSupport = builder.getMainThreadSupport();
    this.mainThreadPoster = this.mainThreadSupport != null ? this.mainThreadSupport.createPoster(this) : null;
    this.backgroundPoster = new BackgroundPoster(this);
    this.asyncPoster = new AsyncPoster(this);
    this.indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
    this.subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes, builder.strictMethodVerification, builder.ignoreGeneratedIndex);
    this.logSubscriberExceptions = builder.logSubscriberExceptions;
    this.logNoSubscriberMessages = builder.logNoSubscriberMessages;
    this.sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
    this.sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
    this.throwSubscriberException = builder.throwSubscriberException;
    this.eventInheritance = builder.eventInheritance;
    this.executorService = builder.executorService;
}

2. 订阅者注册

  • Subscriber传进来的是this,就是上下文Activity。所有订阅者的订阅方法就是这个Activity下的所有订阅方法
    请添加图片描述

  • 获取到EventBus之后,便可以将注册者注册到EventBus中。下面来看一下register方法

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    
    //1.查找订阅者订阅方法
    List<SubscriberMethod> subscriberMethods = this.subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    
    synchronized(this) {
        Iterator var5 = subscriberMethods.iterator();

        while(var5.hasNext()) {
            SubscriberMethod subscriberMethod = (SubscriberMethod)var5.next();
            //2.订阅者的注册过程
            this.subscribe(subscriber, subscriberMethod);
        }

    }
}
  1. 查找订阅者订阅方法
  • 上面代码1处的findSubscriberMethods方法找出一个SubscribeMethod集合。也就传进来的订阅者的所有订阅方法,接下来遍历订阅者的订阅方法完成订阅者的注册操作。
  • 来看findSubscribeMethod方法请添加图片描述
    在这里插入图片描述
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    //1.从缓存处查找是否有订阅方法的集合
    List<SubscriberMethod> subscriberMethods = (List)METHOD_CACHE.get(subscriberClass);
    
    if (subscriberMethods != null) {
        return subscriberMethods;
    } else {
    
        //2.缓存中没有
        if (this.ignoreGeneratedIndex) {
            subscriberMethods = this.findUsingReflection(subscriberClass);
        } else {
            //4.默认为false,调用findUsingInfo方法
            subscriberMethods = this.findUsingInfo(subscriberClass);
        }

        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            //3.找到订阅方法的集合后,放入缓存,以免下次继续查找。
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
}
  • findUsingInfo方法
    请添加图片描述
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    SubscriberMethodFinder.FindState findState = this.prepareFindState();
    findState.initForSubscriber(subscriberClass);

    for(; findState.clazz != null; findState.moveToSuperclass()) {
        //1.通过getSubscribeInfo方法获取订阅者信息。
        findState.subscriberInfo = this.getSubscriberInfo(findState);
        if (findState.subscriberInfo != null) {
            //2.配置了,通过getSubscribeMethods方法获取订阅方法相关的信息。
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            SubscriberMethod[] var4 = array;
            int var5 = array.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                SubscriberMethod subscriberMethod = var4[var6];
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            //3.没有配置。执行findUsingReflectionInSingleClass方法,将订阅方法保存到findState中。  
            this.findUsingReflectionInSingleClass(findState);
        }
    }
    
    //4.通过getMethodsAndRelease方法对findState做回收处理并返回订阅方法的List集合
    return this.getMethodsAndRelease(findState);
}
  • findUsingReflectionInSingleClass
  • 默认肯定是没有配置,所以会调用没有配置的情况下的方法
  • 1处通过反射来获取订阅者中所有的方法,并根据方法的类型、参数和注解来找到订阅方法。
  • 找到订阅方法后将其的相关信息保存到findState中。
private void findUsingReflectionInSingleClass(SubscriberMethodFinder.FindState findState) {
    Method[] methods;
    try {
        //1.
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable var12) {
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }

    Method[] var3 = methods;
    int var4 = methods.length;

    for(int var5 = 0; var5 < var4; ++var5) {
        Method method = var3[var5];
        int modifiers = method.getModifiers();
        if ((modifiers & 1) != 0 && (modifiers & 5192) == 0) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                Subscribe subscribeAnnotation = (Subscribe)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 (this.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 (this.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");
        }
    }

}
  1. 订阅者的注册过程
  • 在查找完订阅者的所有订阅方法以后,便开始对订阅方法进行注册。
  • subscribe方法主要做了两件事:1. 将Subscriptions根据eventType封装到SubscriptionsByEventType中,将subscribedEvents根据subscriber封装到typersBySubscriber中。 2.处理黏性事件
  • subscribe方法
    请添加图片描述
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    //1.
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //2.
    CopyOnWriteArrayList<Subscription> subscriptions = (CopyOnWriteArrayList)this.subscriptionsByEventType.get(eventType);
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList();
        this.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 > ((Subscription)subscriptions.get(i)).subscriberMethod.priority) {
            //3.
            subscriptions.add(i, newSubscription);
            break;
        }
    }

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

    ((List)subscribedEvents).add(eventType);
    if (subscriberMethod.sticky) {
        if (this.eventInheritance) {
            //黏性事件的处理。从stickyEvents事件保存队列中取出该事件类型的事件发送给当前订阅者。
            Set<Entry<Class<?>, Object>> entries = this.stickyEvents.entrySet();
            Iterator var9 = entries.iterator();

            while(var9.hasNext()) {
                Entry<Class<?>, Object> entry = (Entry)var9.next();
                Class<?> candidateEventType = (Class)entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    this.checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = this.stickyEvents.get(eventType);
            this.checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }

}

3. 事件的发送

  • 获取EventBus对象后,可以通过post方法来进行对事件的提交,post方法的源码如下:
  1. 从PostingThreadState对象中取出事件队列,然后在将当前事件插入事件队列。
  2. 最后将事件队列中的事件依次交给postSingleEvent方法进行处理,并移除该事件。
public void post(Object event) {
    //PostingThreadState保存着事件队列和线程状态信息
    PostingThreadState postingState = currentPostingThreadState.get();
    //获取事件队列,并将当前事件插入事件队列。
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    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()) {
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}
  • postSingleEvent
  1. eventInheritance表示是否向上查找事件的父类,它的默认值为true,可以通过EventBusBuilder进行配置。当eventInheritance为true时,通过lookupAllEventTypes找到所有的父类事件并存在List中,然后通过postSingleEventForEventType方法对事件逐一进行处理。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //eventInheritance表示是否向上查找事件的父类,默认为true
    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);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}
  • postSingleEventForType
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        //1.同步取出该事件对应的Subscriptions订阅者对象集合
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        //2.这里遍历Subscriptions集合
        //将事件event和Subscription订阅对象传递给postingState并调用postToSubscription方法对事件进行处理
        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;
}
  • postToSubscription
  • 从订阅对象的订阅方法中取出线程模式(ThreadMode)
  • 根据threadMode来分别处理。
  • 如果提交事件的线程是主线程,那么通过反射直接运行订阅的方法。如果不是,那么需要mainThreadPoster将我们的订阅事件添加到主线程队列中
    mainThreadPoster是HandlerPoster类型的,继承自Handler,通过Handler将订阅方法切换到主线程进行。
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);
    }
}

4. 订阅者取消注册

  • 我们在订阅者注册的时候介绍了typesBySubscriber,它是一个map集合。
  1. 这里通过subscriber得到subscribedTypes(事件类型集合)
  2. 遍历subscribedTypes,并调用unsubscribeByEventType
  3. 将subscriber对应的eventType从typesBySubscriber中移除

public synchronized void unregister(Object subscriber) {
    //1.找到事件类型集合
    List<Class<?>> subscribedTypes = (List)this.typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        Iterator var3 = subscribedTypes.iterator();

        while(var3.hasNext()) {
            //2.遍历subscribedTypes,并调用unsubscribeByEventType
            Class<?> eventType = (Class)var3.next();
            this.unsubscribeByEventType(subscriber, eventType);
        }
        //3.将subscriber对应的eventType从typesBySubscriber中移除
        this.typesBySubscriber.remove(subscriber);
    } else {
        this.logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }

}
  • unsubscribeByEventType
  • 得到订阅对象集合。并在循环中判断如果Subscription的subscriber属性等于传进来的subscriber,则从Subscriptions中移除该Subscription。
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //1.通过eventType来得到对应的Subscription订阅对象集合
    List<Subscription> subscriptions = (List)this.subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();

        for(int i = 0; i < size; ++i) {
            Subscription subscription = (Subscription)subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                --i;
                --size;
            }
        }
    }

}

总结

  • Event事件
  • Subscriptions订阅对象集合(很多个订阅了这个Event的上下文环境,this?)
    请添加图片描述
    请添加图片描述
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值