EventBus与反射

我发现看一段代码,可能当时看的会有点模糊,但过一段时间回来再看的时候会忽然有一种:噢,原来是这么回事的感觉。今天看EventBus源码的时候也有这种感觉。

基本用法

  • 1、注册
	EventBus.getDefault().register(this);

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTestEvent(TestEvent event){
        count++;
        mTextView.setText(count+"");
    }
  • 2、发送Event

    EventBus.getDefault().post(new TestEvent());
    
  • 3、解除注册

    EventBus.getDefault().unregister(this);
    

上面就是EventBus的最基本的用法了。我们就从第一步注册开始,看看EventBus是如何注册的。

一、注册

EventBus.getDefault().register(this);

getDefault 方法如下:

    public static EventBus getDefault() {
        EventBus instance = defaultInstance;
        if (instance == null) {
            synchronized (EventBus.class) {
                instance = EventBus.defaultInstance;
                if (instance == null) {
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
    }

EventBus的获取使用单例模式,确保能够获得一个全局的、唯一的EventBus对象。

register 方法如下:

    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

可以将register分为两部分:

  • 1、首先会执行subscriberMethodFinder.findSubscriberMethods获得当前类中订阅方法的集合(被Subscribe注解修饰的方法的集合)。
    SubscriberMethod就是订阅方法onTestEvent方法属性的类。
    EventBus与反射_第1张图片
  • 2、遍历订阅接收类和方法

注册第一部分:获得该类中所有订阅方法(SubscriberMethod)的集合

1、findSubscriberMethods

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //是否有缓存
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
		//ignoreGeneratedIndex 默认为false,
		//在EventBus构造方法中赋值,为true表示强制使用注解
        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;
        }
    }

可以看到获得订阅方法的集合有两种方法,ignoreGeneratedIndex默认为false,所以会执行findUsingInfo根据索引获得。

2、findUsingInfo

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        //初始化FindState,如果FIND_STATE_POOL数组中有缓存则取出FindState
        //没有则创建一个新的FindState
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
        	//首次订阅,返回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);
    }
  • ①、这里面又出现了一个类FindState,结构如下:
    static class FindState {
        final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
        final Map<Class, Object> anyMethodByEventType = new HashMap<>();
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class<?> subscriberClass;
        Class<?> clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;
    }

同时将FindState保存在数组FIND_STATE_POOL 中作为缓存

    private static final int POOL_SIZE = 4;
    private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
  • ②、首次订阅subscriberInfo为Null,所以会执行findUsingReflectionInSingleClass方法,通过反射来获得订阅的方法。

3、findUsingReflectionInSingleClass

    private void findUsingReflectionInSingleClass(FindState findState) {
        Log.d("EventBus","-------- 执行findUsingReflectionInSingleClass");
        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();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            	//获得方法参数长度
                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.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");
            }
        }
    }

上述方法通过反射获得Class中所有方法,并且通过注解获得方法的修饰符、参数长度和注解。当修饰符是``public、长度是1并且注解是Subscribe时,构造SubscriberMethod对象,并添加到FindState中去。

如果没有找到符合条件的Subscribe修饰的方法,则抛出异常。

到这里我们已经将需要注册的方法都添加到FindState中了,在回到上面第2步findUsingInfo方法中,最后会执行getMethodsAndRelease

关于Java反射: Java反射机制

4、getMethodsAndRelease

    private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        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;
    }

将findState缓存,并返回subscriberMethods 集合。

5、subscribe订阅

在register方法中通过subscriberMethodFinder.findSubscriberMethods获得需要订阅的方法集合后,遍历集合:

    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        Log.d("EventBus","------- register: " + subscriberClass.getName());
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

注册第二部分:subscribe 订阅

    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    
    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    	//获得Event类型
        Class<?> eventType = subscriberMethod.eventType;
        //创建Subscription对象,每个Subscription中存储一个类名和一个方法
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //根据Event类型,获取Subscription集合
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
        	//创建新集合
            subscriptions = new CopyOnWriteArrayList<>();
            //将Event类型作为Key,存储Subscription集合
            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) {
            	//在集合的末尾存储新的Subscription ,集合的长度加1
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        //以类名subscriber最为key,存储该类中注册方法的集合
        //解除注册时使用
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

		...//省略粘性广播
    }

可以看到订阅其实就是将事件存储到Map集合subscriptionsByEventType中。
集合的Key为Event类型,值为Subscription 集合 subscriptions 。

Subscription中存储了subscribersubscriberMethod。如果在Activity中注册的话
subscriber也就是Activity的包名+类名

最后将新的newSubscription 添加到subscriptions 集合中。

二、发送Event

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

post方法如下:

    public void post(Object event) {
        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方法

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        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) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

继续执行postSingleEventForEventType

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

通过eventClass取出在注册的时候存储在subscriptionsByEventType中的subscriptions集合。然后遍历对每一个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 {
                    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);
        }
    }

最后根据threadMode不同,执行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);
        }
    }

最后通过Method的invoke方法,执行已经订阅的方法。

三、unregister

在注册的时候我们已经知道,注册其实就是将Subscription存储在subscriptionsByEventType的Map中。

    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 {
            logger.log(Level.WARNING, "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--;
                }
            }
        }
    }

解除注册就是将subscriptionsByEventType中的EventType移除。

总结

EventBus采用注解与反射的方式来获取订阅方法,所有的订阅方法都添加到Map集合subscriptionByEventType中,发送消息的时候根据消息的类型获得对应的订阅方法,然后通过invoke执行订阅方法。

你可能感兴趣的:(Android源码学习)