Android EventBus源码学习

1、Register(注册过程)

会调用private synchronized voidregister(Object subscriber, boolean sticky, int priority)
其中Object subscriber是注册代码所在函数的对象,就是消息的订阅者(subscriber),sticky指是否是粘性,priority是指订阅的优先级,这个函数的源码是:

List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass());
for (SubscriberMethod subscriberMethod : subscriberMethods) {
	subscribe(subscriber, subscriberMethod, sticky, priority);
}

这个方法详细解释:

(1)SubscriberMethod:这个类封装了三个对象,分别是:

final Method method

java里面的Method类,这个对象方便发送消息之后,调用invoke执行接收消息函数

final ThreadMode threadMode,定义接收到返回的数据所在的线程,有四种情况:
  • PostThread
    订阅者和消息发送者在同一个线程,这是默认的一种情况,
    当需要处理非常简单的单任务的时候,不依赖在主线程里面,建议使用这种模式
  • MainThread
    订阅者在主线程,即UI线程
  • BackgroundThread
    后台线程,订阅者在后台线程
  • Async
    异步线程,在订阅者方法里面实现耗时操作可以使用这种模式,应该避免大数量长时间的使用异步线程来处理消息,因为EventBus使用缓存线程池高效的回收利用线程完成处理的消息
final Class<?> eventType

订阅消息方法的参数类型(这个类型可以是基本类型,也可以是自己封装的类型)

(2) SubscriberMethodFinder

这个类主要用来查找消息订阅者函数

(3) findSubscriberMethods

查找注册消息订阅类的接收消息的函数,详解如下:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
	String key = subscriberClass.getName();//获取注册类的名字,作为map的key
	List<SubscriberMethod> subscriberMethods; //用于存储找到的订阅函数
	synchronized (methodCache) {
		subscriberMethods = methodCache.get(key);//首先查找是否在map里存在订阅函数
	}
	if (subscriberMethods != null) {
		return subscriberMethods;//如果在map里面找到了订阅函数就返回
	}
	subscriberMethods = new ArrayList<SubscriberMethod>();
	Class<?> clazz = subscriberClass;
	HashSet<String> eventTypesFound = new HashSet<String>();
	StringBuilder methodKeyBuilder = new StringBuilder();
	while (clazz != null) {
		String name = clazz.getName();
		if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
			// Skip system classes, this just degrades performance 表明不支持系统的类
			break;
		}
		// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
		Method[] methods = clazz.getDeclaredMethods();//获取注册所在类定义的函数
		for (Method method : methods) {//遍历函数查找订阅消息的函数
			String methodName = method.getName();//获取函数名
			//判断函数是否是以”onEvent开头”,此处说明定义消息订阅函数的时候要以”onEvent”开头
				if (methodName.startsWith(ON_EVENT_METHOD_NAME)) {
					int modifiers = method.getModifiers(); //获取订阅函数的修饰符(public,private,protected)
					//订阅者必须是public修饰的
					if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
						Class<?>[] parameterTypes = method.getParameterTypes(); //获取订阅函数的参数类型
						if (parameterTypes.length == 1) {//只有一个参数</span>
							//获取除”onEvent”之外的字符,用于判断线程类型
							String modifierString = methodName.substring(ON_EVENT_METHOD_NAME.length());
							ThreadMode threadMode;
							//如果订阅函数的名字是”onEvent”,那么默认是PostThread类型
							if (modifierString.length() == 0) { 
								threadMode = ThreadMode.PostThread;
							} else if (modifierString.equals("MainThread")) {
								//如果订阅函数的名字是”onEventMainThread”,那么是MainThread类型
								threadMode = ThreadMode.MainThread; 
							} else if (modifierString.equals("BackgroundThread")) { 
								//如果订阅函数的名字是”onEventBackgroundThread”,那么是BackgroundThread类型
								threadMode = ThreadMode.BackgroundThread; 
							} else if (modifierString.equals("Async")) {
								//如果订阅函数的名字是”onEventAsync”,那么是Async类型
								threadMode = ThreadMode.Async; 
							} else {//特殊情况继续
								if (skipMethodVerificationForClasses.containsKey(clazz)) {
									continue;
								} else {//否则注册消息不合法
									throw new EventBusException("Illegal onEvent method, check for typos: " + method);
								}
							}
							Class<?> eventType = parameterTypes[0];
							methodKeyBuilder.setLength(0);
							methodKeyBuilder.append(methodName);
							methodKeyBuilder.append('>').append(eventType.getName());
							//将订阅函数,订阅函数的类型放到StringBuffer里面
							String methodKey = methodKeyBuilder.toString();
							//Haset的值唯一性,如果之前存在就不添加到订阅集合里面去
							if (eventTypesFound.add(methodKey)) { 
								// Only add if not already found in a sub class
								// SubscriberMethod封装了Method方法,订阅函数所处的线程,订阅函数参数类型的名字             
								subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType)); 
							} 
						}
					} else if (!skipMethodVerificationForClasses.containsKey(clazz)) { 
						Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "." + methodName); 
					}
				} 
			} 
			clazz = clazz.getSuperclass(); 
		}
		//为空,表明没有在注册的类里面找到订阅消息的函数,抛出没有找到用public修饰的订阅函数
		if (subscriberMethods.isEmpty()) { 
			throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called " + ON_EVENT_METHOD_NAME); 
		}else {
			//在map容器里面添加订阅<key=注册函数所属的类,value=List<SubscriberMethod>>
			synchronized (methodCache) { methodCache.put(key, subscriberMethods); } return subscriberMethods; 
		}
	}
}

接下来是真正的消息订阅的过程:

//这个函数只能在同步代码块中执行,因为可能有多个函数注册为订阅者
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
	//获得订阅函数参数的类型
	Class<?> eventType = subscriberMethod.eventType;
	//获取订阅属性
	CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); 
	//封装订阅者,订阅方法,优先级
	Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
	if (subscriptions == null) {
		//新建一个
		subscriptions = new CopyOnWriteArrayList<Subscription>();
		subscriptionsByEventType.put(eventType, subscriptions);
	} else {
		if (subscriptions.contains(newSubscription)) {
			throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType);
		}
	}
	// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
	// subscriberMethod.method.setAccessible(true);
	int size = subscriptions.size();
	for (int i = 0; i <= size; i++) {
		if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
			subscriptions.add(i, newSubscription);//添加一个订阅者
			break;
		}
	}

	List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
	if (subscribedEvents == null) {
		subscribedEvents = new ArrayList<Class<?>>();
		//key=订阅者所属的类,value=订阅函数参数类型名,这里添加是为了到时注销订阅
		typesBySubscriber.put(subscriber, subscribedEvents);
	}
	//添加订阅函数参数属性名
	subscribedEvents.add(eventType); 
	if (sticky) {//是否是粘性注册
		if (eventInheritance) {//默认为true
			// 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>).
			//如果是postSticky的话,stickyEvents这里会有值
			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();
					//这里实际上直接invoke这个stickyEvent方法了
					checkPostStickyEventToSubscription(newSubscription, stickyEvent);
				}
			}
		} else {
			Object stickyEvent = stickyEvents.get(eventType);
			checkPostStickyEventToSubscription(newSubscription, stickyEvent);
		}
	}
}

2、Post(发送消息)

接下来看消息发送过程,开始函数是post(),如果是postSticky(),代码如下:

//粘性发送消息,最近的粘性消息会被保存在内存当中,被之后调用,当然注册的时候使用registerSticky(Object)
public void postSticky(Object event) {
	synchronized (stickyEvents) {
		stickyEvents.put(event.getClass(), event);
	}
	// Should be posted after it is putted, in case the subscriber wants to remove immediately
	post(event);//最后会调用post函数
}

接下来分析Post函数:

public void post(Object event) {
	//获取post线程状态的初始值(ThreadLocal)
	PostingThreadState postingState = currentPostingThreadState.get();
	List<Object> eventQueue = postingState.eventQueue;//post队列
	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;
		}
	}
}

接下来分析postSingleEvent函数:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
	//获取消息所属函数名(“start” = String)
	Class<?> eventClass = event.getClass();
	boolean subscriptionFound = false;//是否找到订阅者
	if (eventInheritance) {//默认为true
		//查找发送消息类型相关的类型,例如public final class String implements Serializable, Comparable<String>
		//此时List里面有String , Serializable , Comparable , CharSequence , Object
		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));
			}
		}
	}
}

接下来分析lookupAllEventTypes()函数:

private List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
	synchronized (eventTypesCache) {
		List<Class<?>> eventTypes = eventTypesCache.get(eventClass);//获取消息类型相关的类型
		if (eventTypes == null) {
			eventTypes = new ArrayList<Class<?>>();
			Class<?> clazz = eventClass;
			while (clazz != null) {
				eventTypes.add(clazz);//添加这个class本身
				addInterfaces(eventTypes, clazz.getInterfaces());//添加这个class完成的interface
				clazz = clazz.getSuperclass();//添加这个class所属的父类
			}
			eventTypesCache.put(eventClass, eventTypes);
		}
		return eventTypes;
	}
} 

接下来分析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;
} 

接下来分析postToSubscription()函数:

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
	//根据消息订阅者所在的线程调用
	switch (subscription.subscriberMethod.threadMode) {
		case PostThread:
			invokeSubscriber(subscription, event);//默认情况直接调用
			break;
		case MainThread:
			if (isMainThread) {
				invokeSubscriber(subscription, event);//如果在UI线程就直接调用
			} else {
				//不在UI线程,通过handler方式发送消息(在UI线程中定义非ui线程订阅函数)
				mainThreadPoster.enqueue(subscription, event);
			}
			break;
		case BackgroundThread:
			if (isMainThread) {
			// UI线程,在线程池(EventBus类中的Executors.newCachedThreadPool)发送消息(在后台线程中定义ui线程订阅函数)
				backgroundPoster.enqueue(subscription, event);
			} else {
				//在后台线程发送消息
				invokeSubscriber(subscription, event); 
			}
			break;
		case Async:
			// 在线程池(EventBus类中的Executors.newCachedThreadPool)发送消息
			asyncPoster.enqueue(subscription, event);
			break;
		default:
			throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
	}
} 

3、UnRegister(注销)

注销订阅,主要在函数unregister()中体现:

public synchronized void unregister(Object subscriber) {
	//获取所有注册函数的参数类型<key=注册所在的类,value=类里面注册函数参数的类型>
	List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);       
	if (subscribedTypes != null) {
		for (Class<?> eventType : subscribedTypes) {
			unubscribeByEventType(subscriber, eventType);//根据参数类型,逐一注销
		}
		typesBySubscriber.remove(subscriber);//移除注册类
	} else {
		Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
	}
}

接下来分析unubscribeByEventType()函数:

private void unubscribeByEventType(Object subscriber, Class<?> eventType) {
	//获取封装了订阅函数的容器
	List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); 
	if (subscriptions != null) {
		int size = subscriptions.size();
		for (int i = 0; i < size; i++) {
			//对于封装的Subscriber和Method等逐一移除
			Subscription subscription = subscriptions.get(i);
			if (subscription.subscriber == subscriber) {
				subscription.active = false;
				subscriptions.remove(i);
				i--;
				size--;
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值