—— 迷茫是什么?迷茫是大事干不了,小事不想干。能力配不上欲望,才華配不上夢想。
前言
時隔多年,那些曾經學過且用過的知識早已記憶模糊。如果不反復研究學習,使用起來也會很生澀,如新知識一樣。本編為鞏固EventBus所寫。一個人為什么要努力,因為喜歡的東西很貴想去的地方都很遠,想愛的人很完美。
一、簡介
官方文檔:https://greenrobot.org/eventbus/documentation/
Github:https://github.com/greenrobot/EventBus
(1)是什么:是一個事件發布/訂閱的輕量級框架。基于觀察者模式,實現組件間的通訊。代碼簡潔且解耦。
(2)有什么用:可以替代傳統的Intent,Handler,Broadcast或接口函數。
?二、基本使用
(1)添加依賴 (不是最新) 基于以前學過的版本
implementation 'org.greenrobot:eventbus:3.0.0'
(2)定義消息事件(可以配置傳遞參數)
public static class MessageEvent { /* Additional fields if needed */ }
(3)定義接收事件的線程方法(發送的事件,將在該方法中收到)
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
(4)EventBus初始化 (與廣播相似,需要訂閱與取消)
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
(5)發送事件
EventBus.getDefault().post(new MessageEvent());
(6)添加混淆
-keepattributes *Annotation*
-keepclassmembers class * {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
簡單的整理了一下 。正確姿勢參考官方文檔。
三、源碼分析
(1)EventBus.getDefault()
* 單例模式 雙重效驗鎖 線程安全 懶加載
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
* 使用構建者配置EventBus 屬性
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus() {
this(DEFAULT_BUILDER);
}
* 屬性簡介
EventBus(EventBusBuilder builder) {
* 保存Event集合
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;
* EventBus訂閱方法
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
* EventBus日志
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
* 無消息發送
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
* 異常事件
throwSubscriberException = builder.throwSubscriberException;
* EventBus繼承關系
eventInheritance = builder.eventInheritance;
* 線程池
executorService = builder.executorService;
}
(2)EventBus.getDefault().register(this)
* 注冊給定的訂閱方以接收事件
public void register(Object subscriber) {
* 利用反射獲取訂閱的類
Class<?> subscriberClass = subscriber.getClass();
* 根據訂閱的類找到 該類下的訂閱方法 -> 1
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
* 便利所有的訂閱方法
for (SubscriberMethod subscriberMethod : subscriberMethods) {
* --> 2
subscribe(subscriber, subscriberMethod);
}
}
}
1.subscriberMethodFinder.findSubscriberMethods(subscriberClass)
* 獲取所有的訂閱方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
* 判斷是否已緩存
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
* ignoreGeneratedIndex 忽略生成的索引 默認為false
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
* 通過反射獲取到訂閱方法列表 -> 1.1
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;
}
}
1.1.findUsingInfo(Class<?> subscriberClass)
* 通過反射獲取到訂閱方法列表
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
* 創建FindState 并初始化
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
* 判斷findState是否已經有緩存訂閱信息
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 {
* 利用反射機制 將訂閱方法信息 存儲在findState 中
findUsingReflectionInSingleClass(findState);
}
* 移除訂閱類
findState.moveToSuperclass();
}
* 回收FindState對象,獲取訂閱方法列表
return getMethodsAndRelease(findState);
}
2.subscribe(Object subscriber, SubscriberMethod subscriberMethod)
* 判斷是否已經注冊/訂閱過該事件
* 按照優先級緩存訂閱事件
* 判斷是否已經緩存在typesBySubscriber中
* 判斷是否是粘性事件 并分發粘性事件
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
* 訂閱方法類型
Class<<?> eventType = subscriberMethod.eventType;
* 創建 訂閱事件
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
* 判斷是否緩存過 訂閱事件 列表
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);
}
}
* 按照優先級緩存訂閱事件 subscriptionsByEventType
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;
}
}
* 判斷是否已經緩存在typesBySubscriber中
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);
* 分發事件 -->2.1
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
2.1checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent)
* 判斷粘性事件是否為空
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
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());
}
}
* 根據線程模式進行事件分發
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);
}
}
* 利用反射 執行訂閱方法
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);
}
}
* 將事件添加到 PendingPostQueue 隊列中 執行handler 從隊列沖取出消息進行處理 并利用反射 執行訂閱方法
void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
總結:
1.利用反射獲取到訂閱類的所有訂閱方法
2.判斷是否已經注冊/訂閱過該事件
3.按照優先級緩存訂閱事件
4.判斷是否是粘性事件 并分發粘性事件 (1)同一個線程 利用反射 執行訂閱方法 (2)不同線程 將事件添加到 PendingPostQueue 隊列中 執行handler 從隊列沖取出消息進行處理 并利用反射 執行訂閱方法
(3)EventBus.getDefault().post(new MessageEvent());
* 發送事件
public void post(Object event) {
* 獲取當前線程的信息
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()) {
* 循環分發事件 -->1
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
1.postSingleEvent(eventQueue.remove(0), postingState);
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
* 判斷是否有繼承關系
if (eventInheritance) {
* 獲取所有類的對象 包含父類與接口
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
* --> 2
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
* 若沒有找到訂閱方法 則調用NoSubscriberEvent
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));
}
}
}
2.postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass)
* 從subscriptionsByEventType中獲取訂閱方法
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;
}
總結:
1.獲取當前線程的信息,將事件添加到當前線程的隊列中
2.判斷是否正在分發 不是則執行postSingleEvent 分發事件
3.判斷是否有繼承關系
是:獲取所有類的對象 包含父類與接口 調用postSingleEventForEventType分發事件
否:調用postSingleEventForEventType分發事件
4.若沒有找到訂閱方法 則分發給NoSubscriberEvent
介紹到這里就結束了 睡覺去了
四、內容推薦
若您發現文章中存在錯誤或不足的地方,希望您能指出!