eventBus源码解析

两种使用方法

不带processor的使用

    //注册
    EventBus.getDefault().register(this);
    //发送
    EventBus.getDefault().post("");
    //处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceve(String s) {

带processor的使用

https://greenrobot.org/eventbus/documentation/subscriber-index/

    //生成路径
	android {
	    defaultConfig {
	        javaCompileOptions {
	            annotationProcessorOptions {
	                arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ]
	            }
	        }
	    }
	}
	//依赖
	dependencies {
	    def eventbus_version = '3.1.1'
	    implementation "org.greenrobot:eventbus:$eventbus_version"
	    annotationProcessor "org.greenrobot:eventbus-annotation-processor:$eventbus_version"
	}
    //index初始化
	public class MyApplication extends Application {
	    @Override
	    public void onCreate() {
	        super.onCreate();
	        LeakCanary.install(this);
	        EventBus.builder().addIndex(new MyEventBusIndex()).build();
	    }
	}

注册源码解析

Event.register中

    public void register(Object subscriber) {
        Class subscriberClass = subscriber.getClass();
        //获取传进来的subscriber类中带有@Subscribe的方法集合
        List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //绑定,会执行粘性事件
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

其中SubscriberMethod类主要是存储注解方法的信息

	public class SubscriberMethod {
        //注解方法
	    final Method method;
        //处理线程
	    final ThreadMode threadMode;
        //参数类 类型
	    final Class eventType;
        //优先级
	    final int priority;
        //是否粘性时间
	    final boolean sticky;
	    /** Used for efficient comparison */
	    String methodString;
	}

findSubscriberMethods是获取注解信息的方法

List findSubscriberMethods(Class subscriberClass) {
    //METHOD_CACHE为map类型,存储第一次解析的数据
    // private static final Map, List> METHOD_CACHE = new ConcurrentHashMap<>();
    List subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //ignoreGeneratedIndex是否使用index(默认是false)
    if (ignoreGeneratedIndex) {
        //通过反射获取类信息
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        //尝试获取index(上述application初始化),若获取失败同findUsingReflection逻辑
        subscriberMethods = findUsingInfo(subscriberClass);
    }
        //设置缓存
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    
}

findUsingReflection反射获取类信息代码

    private List findUsingReflection(Class subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        //while循环是获取父类中带有subscriber的注解方法 例如activity的父类
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

findUsingReflectionInSingleClass方法

private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    //获取类所有的声明方法
    methods = findState.clazz.getDeclaredMethods();
    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();
                        //创建SubscriberMethod类并添加到集合中
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
            } 
    }
}

若ignoreGeneratedIndex为false则会调用findUsingInfo方法

private List findUsingInfo(Class subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //获取index的方法
        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);
}

getSubscriberInfo的方法

private SubscriberInfo getSubscriberInfo(FindState findState) {
    if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
        SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
        if (findState.clazz == superclassInfo.getSubscriberClass()) {
            return superclassInfo;
        }
    }
  //这个就是index的集合
    if (subscriberInfoIndexes != null) {
        for (SubscriberInfoIndex index : subscriberInfoIndexes) {
            SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}

然后在register方法中会调用subscribe方法

    public void register(Object subscriber) {
       //...
        synchronized (this) {
            //循环绑定
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //绑定,会执行粘性事件
                subscribe(subscriber, subscriberMethod);
            }
        }

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //参数的类型
    Class eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
     //创建参数类型的集合
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } 

    int size = subscriptions.size();
    for (int i = 0; i <= size; i++) {
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            //添加newSubscription
            subscriptions.add(i, newSubscription);
            break;
        }
    }
       //....
       //发送粘性事件
       checkPostStickyEventToSubscription(newSubscription, stickyEvent);       
}

其中的subscriptionsByEventType是以对象注册key为,注解类信息集合为值的map数据,在用户发送事件的时候会进行获取
##发送源码(post为例)

public void post(Object event) {
    //PostingThreadState是个ThreadLocal类,线程中数据独立性
    PostingThreadState postingState = currentPostingThreadState.get();
    List eventQueue = postingState.eventQueue;
    //加进事件队列
    eventQueue.add(event);
    if (!postingState.isPosting) {
        postingState.isMainThread = isMainThread();
        postingState.isPosting = true;
        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;
    //...
    //获取所有父类型的信息
    List> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class clazz = eventTypes.get(h);
            //发送事件
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    //...
}

postSingleEventForEventType源码

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
    CopyOnWriteArrayList subscriptions;
    synchronized (this) {
        //在上述的subscriptionsByEventType中根据参数类型获取方法集合
        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源码

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

最终还是会调用反射调用实际方法

你可能感兴趣的:(android开发点滴)