轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/40920453,本文出自:【張鴻洋的博客】
上一篇帶大家初步瞭解了EventBus的使用方式,詳見:Android EventBus實戰 沒聽過你就out了,本篇博客將解析EventBus的源碼,相信能夠讓大家深入理解該框架的實現,也能解決很多在使用中的疑問:爲什麼可以這麼做?爲什麼這麼做不好呢?
1、概述
一般使用EventBus的組件類,類似下面這種方式:
- public class SampleComponent extends Fragment
- {
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- EventBus.getDefault().register(this);
- }
- public void onEventMainThread(param)
- {
- }
- public void onEventPostThread(param)
- {
- }
- public void onEventBackgroundThread(param)
- {
- }
- public void onEventAsync(param)
- {
- }
- @Override
- public void onDestroy()
- {
- super.onDestroy();
- EventBus.getDefault().unregister(this);
- }
- }
public class SampleComponent extends Fragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
public void onEventMainThread(param)
{
}
public void onEventPostThread(param)
{
}
public void onEventBackgroundThread(param)
{
}
public void onEventAsync(param)
{
}
@Override
public void onDestroy()
{
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
大多情況下,都會在onCreate中進行register,在onDestory中進行unregister ;
看完代碼大家或許會有一些疑問:
1、代碼中還有一些以onEvent開頭的方法,這些方法是幹嘛的呢?
在回答這個問題之前,我有一個問題,你咋不問register(this)是幹嘛的呢?其實register(this)就是去當前類,遍歷所有的方法,找到onEvent開頭的然後進行存儲。現在知道onEvent開頭的方法是幹嘛的了吧。
2、那onEvent後面的那些MainThread應該是什麼標誌吧?
嗯,是的,onEvent後面可以寫四種,也就是上面出現的四個方法,決定了當前的方法最終在什麼線程運行,怎麼運行,可以參考上一篇博客或者細細往下看。
既然register了,那麼肯定得說怎麼調用是吧。
EventBus.getDefault().post(param);
調用很簡單,一句話,你也可以叫發佈,只要把這個param發佈出去,EventBus會在它內部存儲的方法中,進行掃描,找到參數匹配的,就使用反射進行調用。
現在有沒有覺得,撇開專業術語:其實EventBus就是在內部存儲了一堆onEvent開頭的方法,然後post的時候,根據post傳入的參數,去找到匹配的方法,反射調用之。
那麼,我告訴你,它內部使用了Map進行存儲,鍵就是參數的Class類型。知道是這個類型,那麼你覺得根據post傳入的參數進行查找還是個事麼?
下面我們就去看看EventBus的register和post真面目。
2、register
EventBus.getDefault().register(this);
首先:
EventBus.getDefault()其實就是個單例,和我們傳統的getInstance一個意思:
- /** Convenience singleton for apps using a process-wide EventBus instance. */
- public static EventBus getDefault() {
- if (defaultInstance == null) {
- synchronized (EventBus.class) {
- if (defaultInstance == null) {
- defaultInstance = new EventBus();
- }
- }
- }
- return defaultInstance;
- }
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
使用了雙重判斷的方式,防止併發的問題,還能極大的提高效率。
然後register應該是一個普通的方法,我們去看看:
register公佈給我們使用的有4個:
- public void register(Object subscriber) {
- register(subscriber, DEFAULT_METHOD_NAME, false, 0);
- }
- public void register(Object subscriber, int priority) {
- register(subscriber, DEFAULT_METHOD_NAME, false, priority);
- }
- public void registerSticky(Object subscriber) {
- register(subscriber, DEFAULT_METHOD_NAME, true, 0);
- }
- public void registerSticky(Object subscriber, int priority) {
- register(subscriber, DEFAULT_METHOD_NAME, true, priority);
- }
public void register(Object subscriber) {
register(subscriber, DEFAULT_METHOD_NAME, false, 0);
}
public void register(Object subscriber, int priority) {
register(subscriber, DEFAULT_METHOD_NAME, false, priority);
}
public void registerSticky(Object subscriber) {
register(subscriber, DEFAULT_METHOD_NAME, true, 0);
}
public void registerSticky(Object subscriber, int priority) {
register(subscriber, DEFAULT_METHOD_NAME, true, priority);
}
本質上就調用了同一個:
- private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) {
- List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
- methodName);
- for (SubscriberMethod subscriberMethod : subscriberMethods) {
- subscribe(subscriber, subscriberMethod, sticky, priority);
- }
- }
private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) {
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
methodName);
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}
四個參數
subscriber 是我們掃描類的對象,也就是我們代碼中常見的this;
methodName 這個是寫死的:“onEvent”,用於確定掃描什麼開頭的方法,可見我們的類中都是以這個開頭。
sticky 這個參數,解釋源碼的時候解釋,暫時不用管
priority 優先級,優先級越高,在調用的時候會越先調用。
下面開始看代碼:
- List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
- methodName);
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
methodName);
調用內部類SubscriberMethodFinder的findSubscriberMethods方法,傳入了subscriber 的class,以及methodName,返回一個List<SubscriberMethod>。
那麼不用說,肯定是去遍歷該類內部所有方法,然後根據methodName去匹配,匹配成功的封裝成SubscriberMethod,最後返回一個List。下面看代碼:
- List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) {
- String key = subscriberClass.getName() + ’.’ + eventMethodName;
- List<SubscriberMethod> subscriberMethods;
- synchronized (methodCache) {
- subscriberMethods = methodCache.get(key);
- }
- if (subscriberMethods != null) {
- return subscriberMethods;
- }
- 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.getMethods();
- for (Method method : methods) {
- String methodName = method.getName();
- if (methodName.startsWith(eventMethodName)) {
- int modifiers = method.getModifiers();
- if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
- Class<?>[] parameterTypes = method.getParameterTypes();
- if (parameterTypes.length == 1) {
- String modifierString = methodName.substring(eventMethodName.length());
- ThreadMode threadMode;
- if (modifierString.length() == 0) {
- threadMode = ThreadMode.PostThread;
- } else if (modifierString.equals(“MainThread”)) {
- threadMode = ThreadMode.MainThread;
- } else if (modifierString.equals(“BackgroundThread”)) {
- threadMode = ThreadMode.BackgroundThread;
- } else if (modifierString.equals(“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());
- String methodKey = methodKeyBuilder.toString();
- if (eventTypesFound.add(methodKey)) {
- // Only add if not already found in a sub class
- 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();
- }
- if (subscriberMethods.isEmpty()) {
- throw new EventBusException(“Subscriber ” + subscriberClass + “ has no public methods called ”
- + eventMethodName);
- } else {
- synchronized (methodCache) {
- methodCache.put(key, subscriberMethods);
- }
- return subscriberMethods;
- }
- }
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) {
String key = subscriberClass.getName() + '.' + eventMethodName;
List<SubscriberMethod> subscriberMethods;
synchronized (methodCache) {
subscriberMethods = methodCache.get(key);
}
if (subscriberMethods != null) {
return subscriberMethods;
}
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.getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith(eventMethodName)) {
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
String modifierString = methodName.substring(eventMethodName.length());
ThreadMode threadMode;
if (modifierString.length() == 0) {
threadMode = ThreadMode.PostThread;
} else if (modifierString.equals("MainThread")) {
threadMode = ThreadMode.MainThread;
} else if (modifierString.equals("BackgroundThread")) {
threadMode = ThreadMode.BackgroundThread;
} else if (modifierString.equals("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());
String methodKey = methodKeyBuilder.toString();
if (eventTypesFound.add(methodKey)) {
// Only add if not already found in a sub class
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();
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called "
+ eventMethodName);
} else {
synchronized (methodCache) {
methodCache.put(key, subscriberMethods);
}
return subscriberMethods;
}
}
呵,代碼還真長;不過我們直接看核心部分:22行:看到沒,clazz.getMethods();去得到所有的方法:
23-62行:就開始遍歷每一個方法了,去匹配封裝了。
25-29行:分別判斷了是否以onEvent開頭,是否是public且非static和abstract方法,是否是一個參數。如果都複合,才進入封裝的部分。
32-45行:也比較簡單,根據方法的後綴,來確定threadMode,threadMode是個枚舉類型:就四種情況。
最後在54行:將method, threadMode, eventType傳入構造了:new SubscriberMethod(method, threadMode, eventType)。添加到List,最終放回。
注意下63行:clazz = clazz.getSuperclass();可以看到,會掃描所有的父類,不僅僅是當前類。
繼續回到register:
- for (SubscriberMethod subscriberMethod : subscriberMethods) {
- subscribe(subscriber, subscriberMethod, sticky, priority);
- }
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
for循環掃描到的方法,然後去調用suscribe方法。
- // Must be called in synchronized block
- private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
- subscribed = true;
- 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 {
- for (Subscription subscription : subscriptions) {
- if (subscription.equals(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<?>>();
- typesBySubscriber.put(subscriber, subscribedEvents);
- }
- subscribedEvents.add(eventType);
- if (sticky) {
- Object stickyEvent;
- synchronized (stickyEvents) {
- stickyEvent = stickyEvents.get(eventType);
- }
- if (stickyEvent != null) {
- // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
- // –> Strange corner case, which we don’t take care of here.
- postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
- }
- }
- }
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
subscribed = true;
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 {
for (Subscription subscription : subscriptions) {
if (subscription.equals(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<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (sticky) {
Object stickyEvent;
synchronized (stickyEvents) {
stickyEvent = stickyEvents.get(eventType);
}
if (stickyEvent != null) {
// If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
// --> Strange corner case, which we don't take care of here.
postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
}
}
}
我們的subscriberMethod中保存了method, threadMode, eventType,上面已經說了;4-17行:根據subscriberMethod.eventType,去subscriptionsByEventType去查找一個CopyOnWriteArrayList<Subscription> ,如果沒有則創建。
順便把我們的傳入的參數封裝成了一個:Subscription(subscriber, subscriberMethod, priority);
這裏的subscriptionsByEventType是個Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> ; 這個Map其實就是EventBus存儲方法的地方,一定要記住!
22-28行:實際上,就是添加newSubscription;並且是按照優先級添加的。可以看到,優先級越高,會插到在當前List的前面。
30-35行:根據subscriber存儲它所有的eventType ; 依然是map;key:subscriber ,value:List<eventType> ;知道就行,非核心代碼,主要用於isRegister的判斷。
37-47行:判斷sticky;如果爲true,從stickyEvents中根據eventType去查找有沒有stickyEvent,如果有則立即發佈去執行。stickyEvent其實就是我們post時的參數。
postToSubscription這個方法,我們在post的時候會介紹。
到此,我們register就介紹完了。
你只要記得一件事:掃描了所有的方法,把匹配的方法最終保存在subscriptionsByEventType(Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> )中;
eventType是我們方法參數的Class,Subscription中則保存着subscriber, subscriberMethod(method, threadMode, eventType), priority;包含了執行改方法所需的一切。
3、post
register完畢,知道了EventBus如何存儲我們的方法了,下面看看post它又是如何調用我們的方法的。
再看源碼之前,我們猜測下:register時,把方法存在subscriptionsByEventType;那麼post肯定會去subscriptionsByEventType去取方法,然後調用。
下面看源碼:
- /** Posts the given event to the event bus. */
- public void post(Object event) {
- PostingThreadState postingState = currentPostingThreadState.get();
- List<Object> eventQueue = postingState.eventQueue;
- eventQueue.add(event);
- if (postingState.isPosting) {
- return;
- } else {
- 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;
- }
- }
- }
/** Posts the given event to the event bus. */
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
if (postingState.isPosting) {
return;
} else {
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;
}
}
}
currentPostingThreadState是一個ThreadLocal類型的,裏面存儲了PostingThreadState;PostingThreadState包含了一個eventQueue和一些標誌位。
- private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
- @Override
- protected PostingThreadState initialValue() {
- return new PostingThreadState();
- }
- }
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
}
把我們傳入的event,保存到了當前線程中的一個變量PostingThreadState的eventQueue中。
10行:判斷當前是否是UI線程。
16-18行:遍歷隊列中的所有的event,調用postSingleEvent(eventQueue.remove(0), postingState)方法。
這裏大家會不會有疑問,每次post都會去調用整個隊列麼,那麼不會造成方法多次調用麼?
可以看到第7-8行,有個判斷,就是防止該問題的,isPosting=true了,就不會往下走了。
下面看postSingleEvent
- private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
- Class<? extends Object> eventClass = event.getClass();
- List<Class<?>> eventTypes = findEventTypes(eventClass);
- boolean subscriptionFound = false;
- int countTypes = eventTypes.size();
- for (int h = 0; h < countTypes; h++) {
- Class<?> clazz = eventTypes.get(h);
- CopyOnWriteArrayList<Subscription> subscriptions;
- synchronized (this) {
- subscriptions = subscriptionsByEventType.get(clazz);
- }
- 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;
- }
- }
- subscriptionFound = true;
- }
- }
- if (!subscriptionFound) {
- Log.d(TAG, ”No subscribers registered for event ” + eventClass);
- if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) {
- post(new NoSubscriberEvent(this, event));
- }
- }
- }
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<? extends Object> eventClass = event.getClass();
List<Class<?>> eventTypes = findEventTypes(eventClass);
boolean subscriptionFound = false;
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(clazz);
}
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;
}
}
subscriptionFound = true;
}
}
if (!subscriptionFound) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
將我們的event,即post傳入的實參;以及postingState傳入到postSingleEvent中。
2-3行:根據event的Class,去得到一個List<Class<?>>;其實就是得到event當前對象的Class,以及父類和接口的Class類型;主要用於匹配,比如你傳入Dog extends Dog,他會把Animal也裝到該List中。
6-31行:遍歷所有的Class,到subscriptionsByEventType去查找subscriptions;哈哈,熟不熟悉,還記得我們register裏面把方法存哪了不?
是不是就是這個Map;
12-30行:遍歷每個subscription,依次去調用postToSubscription(subscription, event, postingState.isMainThread);
這個方法就是去反射執行方法了,大家還記得在register,if(sticky)時,也會去執行這個方法。
下面看它如何反射執行:
- 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);
- } else {
- mainThreadPoster.enqueue(subscription, event);
- }
- break;
- case BackgroundThread:
- 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);
- }
- }
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);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case BackgroundThread:
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);
}
}
前面已經說過subscription包含了所有執行需要的東西,大致有:subscriber, subscriberMethod(method, threadMode, eventType), priority;那麼這個方法:第一步根據threadMode去判斷應該在哪個線程去執行該方法;
case PostThread:
- void invokeSubscriber(Subscription subscription, Object event) throws Error {
- subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
- }
void invokeSubscriber(Subscription subscription, Object event) throws Error {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
}
直接反射調用;也就是說在當前的線程直接調用該方法;
case MainThread:
首先去判斷當前如果是UI線程,則直接調用;否則: mainThreadPoster.enqueue(subscription, event);把當前的方法加入到隊列,然後直接通過handler去發送一個消息,在handler的handleMessage中,去執行我們的方法。說白了就是通過Handler去發送消息,然後執行的。
case BackgroundThread:
如果當前非UI線程,則直接調用;如果是UI線程,則將任務加入到後臺的一個隊列,最終由Eventbus中的一個線程池去調用
executorService = Executors.newCachedThreadPool();。
case Async:將任務加入到後臺的一個隊列,最終由Eventbus中的一個線程池去調用;線程池與BackgroundThread用的是同一個。
這麼說BackgroundThread和Async有什麼區別呢?
BackgroundThread中的任務,一個接着一個去調用,中間使用了一個布爾型變量handlerActive進行的控制。
Async則會動態控制併發。
到此,我們完整的源碼分析就結束了,總結一下:register會把當前類中匹配的方法,存入一個map,而post會根據實參去map查找進行反射調用。分析這麼久,一句話就說完了~~
其實不用發佈者,訂閱者,事件,總線這幾個詞或許更好理解,以後大家問了EventBus,可以說,就是在一個單例內部維持着一個map對象存儲了一堆的方法;post無非就是根據參數去查找方法,進行反射調用。
4、其餘方法
介紹了register和post;大家獲取還能想到一個詞sticky,在register中,如何sticky爲true,會去stickyEvents去查找事件,然後立即去post;
那麼這個stickyEvents何時進行保存事件呢?
其實evevntbus中,除了post發佈事件,還有一個方法也可以:
- 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);
- }
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功能類似,但是會把方法存儲到stickyEvents中去;
大家再去看看EventBus中所有的public方法,無非都是一些狀態判斷,獲取事件,移除事件的方法;沒什麼好介紹的,基本見名知意。
好了,到此我們的源碼解析就結束了,希望大家不僅能夠了解這些優秀框架的內部機理,更能夠體會到這些框架的很多細節之處,併發的處理,很多地方,爲什麼它這麼做等等。
我建了一個QQ羣,方便大家交流。羣號:55032675
———————————————————————————————————-
博主部分視頻已經上線,如果你不喜歡枯燥的文本,請猛戳(初錄,期待您的支持):