EventBus源码分析

###1、概述
EventBus官方定义是Android和java发布/订阅事件总线。eventbus简化组件之间的通讯,将事件发送和接收着分离,避免复杂且容易的依赖关系和生命周期,支持黏性事件。

###2、源码分析
EventBus分为事件发布者和订阅者,先从事件订阅者分析。我们在使用EventBus时通过EventBus.getDefualt()获取EventBus实例对象,通过regester()方法订阅事件。

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

获取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方法中获取当前注册者class对象,然后通过SubsrciberMethodFinder对象通过反射获取class对象中注解方法,在register方法中通过调用subscribeMethodFinder.findSubscriberMethods方法获取注解方法

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> 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;
    }
}

在findSubscriberMethods中先通过Method_Cache查找是否已经有缓存,Method_Cache是一个Map对象,key为注册class对象,value为SubscribleMeMethod对象,有缓存返回缓存中SubscriberMetod集合,没有通过反射获取注册者中被订阅的方法

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

在通过findUsingInfo方法查找注册者订阅方法时,EventBus会创建FindState对象,通过FindState辅助查找当前注册对象获者当前父类中订阅的方法,在EventBus中创建一个大小为4的FindState集合,在findUsingInfo中获取findState对象判断当前集合中是否有可以复用的FindState对象,没有创建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;
    }
    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();
                        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");
        }
    }
}

在findUsingReflectionInSingleClass方法中获取订阅者中所有的方法,判断方法的修饰符和方法参数,如果当前方法中有一个事件类型参数判断当前方法是否有@Subscribe注解,如果有Subscribe注解获取注解中线程模式、是否支持黏性事件、事件类型组装一个SubscribeMetod对象存储FindState字段中,返回到regster中,获取到SubscribeMetod后,遍历SubscribeMethod集合,通过过调用subscribe方法传入当前订阅者和订阅者中有Subscribe方法的集合,在Subscribe中创建一个Subscription对象存储订阅者和SubscribeMethod对象,放入subscriptionsByEventType集合中,创建一个typeBySubscriber map集合存储被订阅者对象和订阅事件类型,然后判断是否有黏性事件接受订阅,在接受黏性事件时判断继承中订阅方法,通过调用checkPostStictyEventToSubscription接受黏性事件,通过stictyEvent中获取黏性事件,通过反射调用订阅者中@Subscribe方法。

 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) {
            // 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<Class>).
            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);
        }
    }
}

在分析post中的方法,在post中我们通过发射事件类型对象,在post通过Thread中TheadLoaclMap获取ThreadLoacl 存储PostingThreadState对象,把当前event事件加入队列中,判断队列是否正在运行,没有运行遍历队列通过调用postSingleEvent方法,处理事件发送,在postSingleEvent中通过subscriptionsByEventType获取在register中封装的subsciptions集合,遍历集合通过调用postToSubscription方法调用method.invoke方法,在postToSubscription中判断订阅者中@Subsrcibe注解方法线程,如果是Posting就是当前post调用线程中执行,Main通过mianThreadPoster切换线程执行,Asyc通过asynPoster通过EventBus线程池做线程切换。

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

###3、总结
EventBus通过register注册,分为两种普通订阅和黏性订阅事件,在register中通过通过subscriberMethodFinder对象查找订阅者中订阅方法,在subscriberMethodFinder中通过FindState使用反射获取@Subscribe注解中的方法,获取方法执行线程是否黏性事件等,EventBus维护一个大小为4的FindState集合,提供重复使用,查找被注解的方法后封装成SubscriberMethod,把SubscriberMethod放到Map缓存中,下次重新打开activity或者订阅者不需要通过反射获取,当前map集合是ConcurrentHashmap保证线程安全,register查找订阅方法后把订阅对象和SubsciblerMethod存在到Subscription中,判断是否有黏性事件,如果StickEvent不为空,遍历Subsciptions集合如果eventType类型一样发射事件,用户通过post发射事件时是通过遍历register中Subscription集合,通过反射调用订阅者中方法,在subscription中存储着订阅者对象和方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值