程序笔记   发布时间:2022-07-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了05、Android--EventBus原理解析大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

EventBus原理

EventBus构造方法

当我们要使用EventBus时,首先会调用EventBus.getDefault()来获取EventBus实例。

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

单例模式,采用了双重检查模式 (DCL)。接下来查看 EventBus 的构造方法:

public EventBus() {
    this(DEFAULT_BUILDER);
}

这里DEFAULT_BUILDER是默认的EventBusBuilder,用来构造EventBus:

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

this调用了EventBus的另一个构造方法,如下所示:

EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
    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进行配置,这里采用了建造者模式。

订阅者注册

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

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    // findSubscriberMethods方法找出一个SubscriberMethod的集合,也就是传进来的订阅者的
    // 所有订阅方法,接下来遍历订阅者的订阅方法来完成订阅者的注册操作。
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

查找订阅者的订阅方法

register方法做了两件事:一件事是查找订阅者的订阅方法,另一件事是订阅者的注册。

在SubscriberMethod类中,主要用来保 存订阅方法的Method对象、线程模式、事件类型、优先级、是否是黏性事件等属性。下面就来查看findSubscriberMethods方法,如下所示:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    // 从缓存中查找是否有订阅方法的集合,如果找到了就立马返回。
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
	// 如果缓存没有,则根据ignoreGeneratedIndex属性的值来选择采用何种方法来查找订阅方法的集合。
    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 属性表示是否忽略注解器生成的 MyEventBusIndex。

我们在项目中经常通过EventBus单例模式来获取默认的EventBus对 象,也就是ignoreGeneratedIndex为false的情况,这种情况调用了findUsingInfo方法:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    SubscriberMethodFinder.FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        // 通过 getSubscriberInfo 方法来获取订阅者信息
        findState.subscriberInfo = getSubscriberInfo(findStatE);
        if (findState.subscriberInfo != null) {
            // 调用subscriberInfo的getSubscriberMethods方法便可以得 到订阅方法相关的信息
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventTypE)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            // 将订阅方法保存到findState中
            findUsingReflectionInSingleClass(findStatE);
        }
        findState.moveToSuperclass();
    }
    // 回收处理并返回订阅方法的List集合
    return getMethodsAndRelease(findStatE);
}

默认情况下是没有配置MyEventBusIndex的,因此现在查看一下findUsingReflectionInSingleClass方法的执行过程,如下所示:

private void findUsingReflectionInSingleClass(SubscriberMethodFinder.FindState findStatE) {
    Method[] methods;
    try {
	   // 通过反射来获取订阅者中所有的方法,并根据方法的类型、参数和注解来找到订阅方法。
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        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");
        }
    }
}

找到订阅方法后将订阅方法的相关信息保存到findState中。

订阅者的注册过程

在查找完订阅者的订阅方法以后便开始对所有的订阅方法进行注册。我们再回到 register方法中,subscribe方法来对订阅方法进行注册,如下所示:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    // 根据subscriber(订阅者)和subscriberMethod(订阅方法)创建一个Subscription(订阅对象)
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    // 根据eventType(事件类型)获取Subscriptions(订阅对象集合)
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventTypE);
    // 如果 Subscriptions为null则重新创建,并将Subscriptions根据eventType保存在subscriptionsByEventType(Map集合)
    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;
        }
    }
	// 通过 subscriber获取subscribedEvents(事件类型集合)。
    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);
        }
    }
}

subscribe方法主要就做了两件事:一件事是将Subscriptions根据eventType封装到subscriptionsByEventType

中,将subscribedEvents根据subscriber封装到typesBySubscriber中;第二件事就是对黏性事件的处理。

事件的发送

在获取EventBus对象以后,可以通过post方法来进行对事件的提交。post方法的源码如下所示:

public void post(Object event) {
    // PosTingThreadState保存事件队列和线程状态信息
    EventBus.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对象中取出事件队列,然后再将当前的事件插入事件队列。最后将队列中的

事件依次交由 postSingleEvent 方法进行处理,并移除该事件。之后查看postSingleEvent方法:

private void postSingleEvent(Object event, EventBus.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) {
            Log.d(tag, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

evenTinheritance 表示是否向上查找事件的父类,它的默认值为 true,可以通过在EventBusBuilder中进行

配置。当evenTinheritance为true时,则通过lookupAllEventTypes找到所有的父类事件并存在List中,然后通过

postSingleEventForEventType方法对事件逐一处理。postSingleEventForEventType方法的源码如下所示:

private Boolean postSingleEventForEventType(Object event, EventBus.PosTingThreadState posTingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        // 同步取出该事件对应的Subscriptions(订阅对象集合)。
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        // 遍历Subscriptions, 将事件 event 和对应的 Subscription(订阅对象)传递给
        // posTingState 并调用postToSubscription方法对事件进 行处理。
        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方法:

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

取出订阅方法的threadMode(线程模式),之后根据threadMode来分别处理。如果threadMode是

@H_910_4@mAIN,若提交事件的线程是主线程,则通过反射直接运行订阅的方法;若其不是主线程,则需要

@H_910_4@mainThreadPoster 将我们的订阅事件添加到主线程队列中。mainThreadPoster 是HandlerPoster类型的,继承

自Handler,通过Handler将订阅方法切换到主线程执行。

订阅者取消注册

取消注册则需要调用unregister方法,如下所示:

public synchronized void unregister(Object subscriber) {
    // 通过 subscriber找到subscribedTypes(事件类型集合)。
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            // 遍历 subscribedTypes,并调用 unsubscribeByEventType方法
            unsubscribeByEventType(subscriber, eventTypE);
        }
        // 将subscriber对应的eventType从 typesBySubscriber 中移除。
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(tag, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

我们在订阅者注册的过程中讲到过typesBySubscriber,它是一个map集合。接下来看unsubscribeByEventType方法:

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

注释处通过eventType来得到对应的Subscriptions(订阅对象集合),并在for循环中判断如果 Subscription (订阅对象)的subscriber(订阅者)属性等于传进来的subscriber,则从Subscriptions中移除该Subscription。

大佬总结

以上是大佬教程为你收集整理的05、Android--EventBus原理解析全部内容,希望文章能够帮你解决05、Android--EventBus原理解析所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。