EventBus源码阅读

1、使用
/**
* 页面A
*/
// 注册EventBus
EventBus.getDefault().register(this);

@Subscribe(threadMode = ThreadMode.MAIN)
public void callBack(String s) {
	// 事件处理
}

// 注销EventBus
@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
}
/**
* 页面B
*/
// 发送事件
EventBus.getDefault().post("ABC");
2、源码阅读
2.1 EventBus.getDefault();
/**
* EventBus类
*/
// 单例创建EventBus,保证全局对象唯一
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无参构造方法
public EventBus() {
	// private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
	this(DEFAULT_BUILDER);
}
// 通过Builder初始化EventBus的一些配置,配置解耦
EventBus(EventBusBuilder builder) {
    logger = builder.getLogger();
    // private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    // key是事件的class字节码对象,value存储着所有订阅了该事件的集合
    subscriptionsByEventType = new HashMap<>();
    // private final Map<Object, List<Class<?>>> typesBySubscriber;
    // key是订阅者对象,即register时传进来的this,value是事件的class字节码对象的集合
    // 假设某个Activity里注册了四个事件方法,那么这个HashMap最终存储的key就是这个Activity对象,而Value就是四个参数事件的集合
    typesBySubscriber = new HashMap<>();
    // 保存粘性事件
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadSupport = builder.getMainThreadSupport();
    // 主线程发送器
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
    // background发送器
    backgroundPoster = new BackgroundPoster(this);
    // async异步发送器
    asyncPoster = new AsyncPoster(this);
    indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
    // 创建一个SubscriberMethodFinder对象
    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;
}
2.2 register(this);
/**
* EventBus类
*/
public void register(Object subscriber) {
	// 获取this的字节码对象
    Class<?> subscriberClass = subscriber.getClass();
    // 请看(1)
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
    	// 遍历当前页面找到的所有方法
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
        	// 请看(2)
            subscribe(subscriber, subscriberMethod);
        }
    }
}
/**
* (1)SubscriberMethodFinder类
*/
// 该方法的最终目的就是找出当前这个页面所有的注解方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
	// 先从缓存中查找
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
    	// 缓存中有,则直接返回
        return subscriberMethods;
    }
	// 是否忽略注解器生成的MyEventBusIndex类,如没有通过Builder中设置该参数,默认是false
    if (ignoreGeneratedIndex) {
    	// 强制使用反射的模式找出这些注解的方法
    	// 这个方法最终也是调用(6)
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
    	// 请看(3)
        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;
    }
}

// (3)
// subscriberClass = 外部传进来的this.getClass()
// 该方法会根据条件判断,有两种模式选择
// 如果没有设置subscriberInfoIndexes,最终还是走强制使用反射的找出所有方法的那个模式
// 如果设置了subscriberInfoIndexes,那么就很简单了,就去获取该方法里设置的信息
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
	// 简单点理解,就是初始化FindState,请看(4)
    FindState findState = prepareFindState();
    // 这个方法仅仅做了一些初始化操作
    // this.subscriberClass = clazz = subscriberClass;
    // skipSuperClasses = false
    // subscriberInfo = null
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
    	// 请看(5)
        findState.subscriberInfo = getSubscriberInfo(findState);
        if (findState.subscriberInfo != null) {
        	// 外部设置了SubscriberInfoIndex,获取到外部的subscriberInfo
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
            	// 最终和findUsingReflectionInSingleClass一样,添加到findState的List里
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
        	// 如果外部没有设置SubscriberInfoIndex,最终还是走强制使用反射找出所有的方法模式
        	// 请看(6)
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

// (4)
// 实际就是从4个元素的池子中找出复用,没有就创建
private FindState prepareFindState() {
    synchronized (FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            FindState state = FIND_STATE_POOL[i];
            if (state != null) {
                FIND_STATE_POOL[i] = null;
                return state;
            }
        }
    }
    return new FindState();
}

// (5)
// 这个方法的结论是,如果外部没有设置SubscriberInfoIndex,那么这个方法就会返回null
private SubscriberInfo getSubscriberInfo(FindState findState) {
	// 上面subscriberInfo = null,所以下面的判断进不去
    if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
        SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
        if (findState.clazz == superclassInfo.getSubscriberClass()) {
            return superclassInfo;
        }
    }
    // 这个SubscriberInfoIndex就是我前面在(3)地方提到的,需要通过Builder进行设置,如果没有设置,那么下面的方法也进不来
    if (subscriberInfoIndexes != null) {
    	// 如果设置了,那么通过外部设置的SubscriberInfoIndex设置的SubscriberInfo ,获取SubscriberInfo 
    	// 这个等下再说。
        for (SubscriberInfoIndex index : subscriberInfoIndexes) {
            SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}

// (6)
//  反射找出当前注册所在页面的所有注解方法
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) {
        // 省略
    }
    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注解
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    if (findState.checkAdd(method, eventType)) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        // 最终创建一个SubscriberMethod对象,把当前这个method,参数的字节码对象,线程模式,
                        // 优先级,是否粘性封住到这个对象。添加到findState的List里。
                        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");
        }
    }
}

接着我们来说一下,通过外部设置SubscriberInfoIndex的情况。
1、首先我们可以自定义SubscriberInfoIndex

public class EventBusIndexTest {

    public void testManualIndexWithoutAnnotation() {
        SubscriberInfoIndex index = new SubscriberInfoIndex() {
            @Override
            public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
                SubscriberMethodInfo[] methodInfos = {
                        new SubscriberMethodInfo("someMethodWithoutAnnotation", String.class)
                };
                return new SimpleSubscriberInfo(EventBusIndexTest.class, false, methodInfos);
            }
        };
		// 设置SubscriberInfoIndex 
        EventBus eventBus = EventBus.builder().addIndex(index).build();
        eventBus.register(this);
        eventBus.post("Yepp");
        eventBus.unregister(this);
    }

    public void someMethodWithoutAnnotation(String value) {
        // 事件回调及处理
    }
}

2、3.0版本中,EventBus提供了一个EventBusAnnotationProcessor注解处理器来在编译期通过读取@Subscribe()注解并解析,处理其中所包含的信息,然后自动生成java类来保存所有订阅者关于订阅的信息,这样就比在运行时使用反射来获得这些订阅者的信息速度要快。本质上和上面我们自定义的没什么不同,仅仅下面这个代码通过注解处理器自动生成的而已。

/**
 * This class is generated by EventBus, do not edit.
 */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(org.greenrobot.eventbusperf.testsubject.PerfTestEventBus.SubscriberClassEventBusAsync.class,
                true, new SubscriberMethodInfo[]{
                new SubscriberMethodInfo("onEventAsync", TestEvent.class, ThreadMode.ASYNC),
        }));

        putIndex(new SimpleSubscriberInfo(TestRunnerActivity.class, true, new SubscriberMethodInfo[]{
                new SubscriberMethodInfo("onEventMainThread", TestFinishedEvent.class, ThreadMode.MAIN),
        }));
    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

接着,我们回头分析(2)

/**
* EventBus类
*/
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
	// 获取该方法的参数的字节码对象,比如String.class
    Class<?> eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    // 从HashMap获取String.class对应的Subscription对象集合
    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);
        }
    }
	// 根据优先级,添加到CopyOnWriteArrayList里
    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;
        }
    }
    
	// 把传进来的this.getClass和参数String.class添加到subscribedEvents成员变量里
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);
	
	// 是否是粘性事件
    if (subscriberMethod.sticky) {
    	// eventInheritance默认是false
        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 {
        	// 从stickyEvents集合里拿出事件,如果有该事件,立即分发sticky事件
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

至此,EventBus注册流程已分析完毕。接着我们看看是怎么post事件的?

2.3 EventBus.getDefault(this).post(“ABC”);
/**
* EventBus类
*/
public void post(Object event) {
	// 获取当前线程保存的PostingThreadState对象
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    // 把发送的事件添加到List里
    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()) {
            	// 循环发送事件,请看(8)
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

// (8)
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass(); // String.class
    boolean subscriptionFound = false;
    // eventInheritance默认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 {
    	// (9)
        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));
        }
    }
}

// (9)
// 参数1,事件,比如"ABC"
// 参数2,当前线程的postingState对象
// 参数3,事件的字节码对象,比如String.class
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
    	// 获取参数是String.class的所有注解方法
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
    	// 遍历所有参数是String.class的注解方法
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted;
            try {
            	// 请看(10)根据线程发送事件
                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;
}

// (10)
// 参数3,当前运行的线程是否是主线程
// 就以Main分析,其他的一样道理。
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    switch (subscription.subscriberMethod.threadMode) {
        case POSTING:
            invokeSubscriber(subscription, event);
            break;
        case MAIN:
        	// 事件处理方法要求再主线程Main中执行
            if (isMainThread) {
            	// 当前运行的就是主线程,所以直接反射调用事件处理方法即可。
                invokeSubscriber(subscription, event);
            } else {
            	// 当前运行线程非主线,那么就需要切换到主线程Looper再反射调用事件处理方法
                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);
    }
}

// 反射调用事件处理方法
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);
    }
}
3、总结

业内对EventBus的主要争论点是在于EventBus使用反射会出现性能问题。实际上在EventBus里我们可以看到不仅可以使用注解处理器预处理获取订阅信息,EventBus也会将订阅者的方法缓存到METHOD_CACHE里避免重复查找,所以只有在最后invoke()方法的时候会比直接调用多出一些性能损耗,但是这些对于我们移动端来说是完全可以忽略的。所以盲目的说因为性能问题而觉得EventBus不值得使用显然是不负责任的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值