EventBus3.0源码学习(一)

在看源码之前,需要掌握的主要知识点:集合、反射、注解。
框架基本上是用这三方面的知识点写的,没掌握的最好去掌握下,不然看的时候会晕头转向。

一、注册源码解析

注册的一系列流程,其流程图(来自网络)如下:

这里写图片描述

      我们在使用EventBus的时候,首先做的第一件事就是给事件注册对象了,通俗来讲就是说要接收消息,需要登记信息,方便有消息可以通知到你。
      那么EventBus是如何注册信息的呢?又是如何接收事件?
我们带着疑问看代码,效果会更好。
注册订阅者代码:

    //将当前对象进行注册,表示这个对象要接收事件
    EventBus.getDefault().register(this);

注册源码:

    public void register(Object subscriber) {
        //获取订阅者的Class类型
        Class<?> subscriberClass = subscriber.getClass();
        //根据订阅者的Class类型,获取订阅者的订阅方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

List< SubscriberMethod > subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
这句代码表示的是:通过订阅者的Class类型获取订阅者的所有的订阅方法。那它是如何获取所有的订阅方法的呢?

我们再看一下findSubscriberMethods方法的源码

 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
 //先从缓存中查找是否存在订阅方法
        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.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

上面的源码在查找订阅方法信息是用了两种方式,如下所示:

 if (ignoreGeneratedIndex) {
     //利用反射来获取订阅类中的订阅方法信息      
                subscriberMethods = findUsingReflection(subscriberClass);
            } else {
      //从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息     
                subscriberMethods = findUsingInfo(subscriberClass);
            }

ignoreGeneratedIndex的判断是看你的build配置文件是否配置相关注解处理器信息如下:
这里写图片描述

要说两种方式区别无非就是性能和速度,相对说注解处理比反射来的好,看下面的图就清楚了。

这个方法的大致逻辑是这样:
     先从缓存中查找订阅方法信息,如果没有就利用反射或注解来获取订阅方法信息。

1、使用注解处理器
findUsingInfo(Class< ? > subscriberClass)

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

EventBus提供了一个EventBusAnnotationProcessor注解处理器来在编译期通过读取@Subscribe()注解并解析,
处理其中所包含的信息,然后生成java类来保存所有订阅者关于订阅的信息,这样就比在运行时使用反射来获得这些订阅者的
信息速度要快。
EventBus 3.0使用的是编译时注解,而不是运行时注解。通过索引的方式去生成回调方法表,通过表可以看出,极大的提高了性能。

这里写图片描述

2、通过反射获取的订阅方法信息

findUsingReflection(subscriberClass)源码

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
     while (findState.clazz != null) {
          //通过发射获得订阅方法信息
          findUsingReflectionInSingleClass(findState);
            //查找父类的订阅方法信息
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

FindState是一个实体类,用来保存订阅者和订阅方法的信息,以及校验订阅方法。写了那么多,其实最终是调用findUsingReflectionInSingleClass(findState)来获得订阅方法的相关信息。
看代码:

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) {
            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();
                //方法至少要有一个参数,否则抛出异常
                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");
            }
        }
    }

开始订阅事件的源码:
订阅者有了,订阅方法也有了。接下来是当做参数进行订阅,

  // 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);
        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();
        //根据优先级来添加订阅者对象
        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);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            //将订阅者对象和订阅者事件保存
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                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);
            }
        }
    }

注册只有一句代码,但是深入里面去,却是做了许许多多的工作。
其实,做了那么多的工作,无非就是存储订阅者的相关信息(订阅者、订阅方法、事件对象等),为后面的事件分发做的铺垫。

订阅逻辑:

    1. 首先调用register()注册订阅对象。
    2. 根据订阅对象获取该订阅对象的所有订阅方法。
    3.   subscriptionsByEventType.put(eventType, subscriptions),根据该订阅者的所有订阅的事件类型,将订阅者存入到每个以 事件类型为key, 以订阅者信息(subscriptions)为values的map集合中。
    4.  typesBySubscriber.put(subscriber, subscribedEvents),然后将订阅事件添加到以订阅者为key ,以订阅者所有订阅事件为values的map集合中.  

二、事件分发解析

事件分发的流程图(来源网络)
这里写图片描述

      注册订阅者是为了后面的事件分发,以便知道该将事件发送给谁,而事件的接收就是订阅者的订阅方法。
事件分发代码:

    EventBus.getDefault().post(new Event());

看post方法的源码:
参数即要发送的事件对象

 public void post(Object event) {
     //获取当前线程的状态
        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;
            }
        }
    }

PostingThreadState 是EventBust的静态内部类,它保存当前线程的事件队列和线程状态。

final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<Object>();//当前线程的事件队列
         boolean isPosting;//是否有事件正在分发
         boolean isMainThread;//post的线程是否是主线程
         Subscription subscription;//订阅者
         Object event;//订阅事件
         boolean canceled;//是否取消
     }

参数一:事件对象
参数二:发送状态
postSingleEvent(eventQueue.remove(0), postingState)执行源码

  private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
      //获取事件对象的Class类型
        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) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

postSingleEventForEventType(event, postingState, eventClass)
看了那么多的源码才发现这个方法才是罪魁祸首。最终发射事件的方法。
那好接着看看他的源码:

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

postToSubscription(subscription, event, postingState.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 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(subscription, event)
参数一:订阅者
参数二:事件对象
最后是通过反射调用实现的。

 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. 循环取出队列中的事件。
3. 获取订阅者集合,然后遍历,最后通过反射调用订阅者的订阅方法。

三、取消注册解析

 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 {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }
 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--;
                }
            }
        }
    }

取消注册逻辑:

1、首先根据订阅者获取所有订阅事件。
2、遍历订阅事件集合。
3、根据订阅事件获取订阅该事件的订阅者集合。
4、遍历订阅者集合,然后根据传入的订阅者做比较,判断是否是同一订阅者。如果是则移除,反之。

参考:http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EventBus是一种用于Android应用程序中发布/订阅事件的库。它遵循发布-订阅模式,允许不同组件之间进行松散耦合的通信。 在基于EventBus 3.0的APP开发中,你可以按照以下步骤进行: 1. 添加EventBus依赖 在项目的build.gradle文件中添加以下代码: ``` dependencies { implementation 'org.greenrobot:eventbus:3.2.0' } ``` 2. 创建事件类 创建一个事件类,它将包含你需要发送和接收的数据。例如: ``` public class MessageEvent { public final String message; public MessageEvent(String message) { this.message = message; } } ``` 3. 注册订阅者 在需要接收事件的组件中,注册订阅者。例如,在Activity中: ``` @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } ``` 4. 发布事件 在需要发送事件的组件中,发布事件。例如,在Activity中: ``` EventBus.getDefault().post(new MessageEvent("Hello, world!")); ``` 5. 处理事件 在订阅者中,创建一个方法来处理接收到的事件。例如,在Activity中: ``` @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) { // Do something with the event Toast.makeText(this, event.message, Toast.LENGTH_SHORT).show(); } ``` 以上就是基于EventBus 3.0的APP开发的基本步骤。通过使用EventBus,你可以轻松地在不同组件之间传递数据,从而实现应用程序中的松散耦合通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值