—— 迷茫是什么荷鼠?迷茫是大事干不了句携,小事不想干。能力配不上欲望允乐,才華配不上夢(mèng)想矮嫉。
前言
時(shí)隔多年削咆,那些曾經(jīng)學(xué)過(guò)且用過(guò)的知識(shí)早已記憶模糊。如果不反復(fù)研究學(xué)習(xí)蠢笋,使用起來(lái)也會(huì)很生澀拨齐,如新知識(shí)一樣。本編為鞏固EventBus所寫(xiě)昨寞。一個(gè)人為什么要努力瞻惋,因?yàn)橄矚g的東西很貴想去的地方都很遠(yuǎn),想愛(ài)的人很完美援岩。
一歼狼、簡(jiǎn)介
官方文檔:https://greenrobot.org/eventbus/documentation/
Github:https://github.com/greenrobot/EventBus
(1)是什么:是一個(gè)事件發(fā)布/訂閱的輕量級(jí)框架∠砘常基于觀察者模式羽峰,實(shí)現(xiàn)組件間的通訊。代碼簡(jiǎn)潔且解耦添瓷。
(2)有什么用:可以替代傳統(tǒng)的Intent,Handler,Broadcast或接口函數(shù)梅屉。
?二、基本使用
(1)添加依賴 (不是最新) 基于以前學(xué)過(guò)的版本
implementation 'org.greenrobot:eventbus:3.0.0'
(2)定義消息事件(可以配置傳遞參數(shù))
public static class MessageEvent { /* Additional fields if needed */ }
(3)定義接收事件的線程方法(發(fā)送的事件鳞贷,將在該方法中收到)
@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)發(fā)送事件
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);
}
簡(jiǎn)單的整理了一下 。正確姿勢(shì)參考官方文檔搀愧。
三惰聂、源碼分析
(1)EventBus.getDefault()
* 單例模式 雙重效驗(yàn)鎖 線程安全 懶加載
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
* 使用構(gòu)建者配置EventBus 屬性
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus() {
this(DEFAULT_BUILDER);
}
* 屬性簡(jiǎn)介
EventBus(EventBusBuilder builder) {
* 保存Event集合
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
* 線程調(diào)度
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;
* 無(wú)消息發(fā)送
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
* 異常事件
throwSubscriberException = builder.throwSubscriberException;
* EventBus繼承關(guān)系
eventInheritance = builder.eventInheritance;
* 線程池
executorService = builder.executorService;
}
(2)EventBus.getDefault().register(this)
* 注冊(cè)給定的訂閱方以接收事件
public void register(Object subscriber) {
* 利用反射獲取訂閱的類(lèi)
Class<?> subscriberClass = subscriber.getClass();
* 根據(jù)訂閱的類(lèi)找到 該類(lèi)下的訂閱方法 -> 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 忽略生成的索引 默認(rèn)為false
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
* 通過(guò)反射獲取到訂閱方法列表 -> 1.1
subscriberMethods = findUsingInfo(subscriberClass);
}
* 訂閱方法列表為空時(shí) 拋出異常
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber" + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
* 緩存該訂閱類(lèi)的所有訂閱方法
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
1.1.findUsingInfo(Class<?> subscriberClass)
* 通過(guò)反射獲取到訂閱方法列表
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
* 創(chuàng)建FindState 并初始化
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
* 判斷findState是否已經(jīng)有緩存訂閱信息
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 {
* 利用反射機(jī)制 將訂閱方法信息 存儲(chǔ)在findState 中
findUsingReflectionInSingleClass(findState);
}
* 移除訂閱類(lèi)
findState.moveToSuperclass();
}
* 回收FindState對(duì)象,獲取訂閱方法列表
return getMethodsAndRelease(findState);
}
2.subscribe(Object subscriber, SubscriberMethod subscriberMethod)
* 判斷是否已經(jīng)注冊(cè)/訂閱過(guò)該事件
* 按照優(yōu)先級(jí)緩存訂閱事件
* 判斷是否已經(jīng)緩存在typesBySubscriber中
* 判斷是否是粘性事件 并分發(fā)粘性事件
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
* 訂閱方法類(lèi)型
Class<<?> eventType = subscriberMethod.eventType;
* 創(chuàng)建 訂閱事件
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
* 判斷是否緩存過(guò) 訂閱事件 列表
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
* 判斷是否已經(jīng)訂閱過(guò) 訂閱過(guò)則拋出異常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber" + subscriber.getClass() + " already registered to event "+ eventType);
}
}
* 按照優(yōu)先級(jí)緩存訂閱事件 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;
}
}
* 判斷是否已經(jīng)緩存在typesBySubscriber中
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
* 判斷是否是粘性事件 并分發(fā)粘性事件
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();
* 分發(fā)事件
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
* 分發(fā)事件 -->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());
}
}
* 根據(jù)線程模式進(jìn)行事件分發(fā)
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);
}
}
* 利用反射 執(zhí)行訂閱方法
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 隊(duì)列中 執(zhí)行handler 從隊(duì)列沖取出消息進(jìn)行處理 并利用反射 執(zhí)行訂閱方法
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");
}
}
}
}
總結(jié):
1.利用反射獲取到訂閱類(lèi)的所有訂閱方法
2.判斷是否已經(jīng)注冊(cè)/訂閱過(guò)該事件
3.按照優(yōu)先級(jí)緩存訂閱事件
4.判斷是否是粘性事件 并分發(fā)粘性事件 (1)同一個(gè)線程 利用反射 執(zhí)行訂閱方法 (2)不同線程 將事件添加到 PendingPostQueue 隊(duì)列中 執(zhí)行handler 從隊(duì)列沖取出消息進(jìn)行處理 并利用反射 執(zhí)行訂閱方法
(3)EventBus.getDefault().post(new MessageEvent());
* 發(fā)送事件
public void post(Object event) {
* 獲取當(dāng)前線程的信息
PostingThreadState postingState = currentPostingThreadState.get();
* 將事件添加到當(dāng)前線程的隊(duì)列中
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
* 判斷是否正在分發(fā) 不是則繼續(xù)執(zhí)行
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()) {
* 循環(huán)分發(fā)事件 -->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;
* 判斷是否有繼承關(guān)系
if (eventInheritance) {
* 獲取所有類(lèi)的對(duì)象 包含父類(lèi)與接口
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);
}
* 若沒(méi)有找到訂閱方法 則調(diào)用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;
}
總結(jié):
1.獲取當(dāng)前線程的信息咱筛,將事件添加到當(dāng)前線程的隊(duì)列中
2.判斷是否正在分發(fā) 不是則執(zhí)行postSingleEvent 分發(fā)事件
3.判斷是否有繼承關(guān)系
是:獲取所有類(lèi)的對(duì)象 包含父類(lèi)與接口 調(diào)用postSingleEventForEventType分發(fā)事件
否:調(diào)用postSingleEventForEventType分發(fā)事件
4.若沒(méi)有找到訂閱方法 則分發(fā)給NoSubscriberEvent
介紹到這里就結(jié)束了 睡覺(jué)去了
四庶近、內(nèi)容推薦
- 《CSDN》《簡(jiǎn)書(shū)》
- 《Android Jetpack組件之架構(gòu)組件總結(jié)》
- 《Android 網(wǎng)絡(luò)請(qǐng)求框架okhttp學(xué)習(xí)筆記》
- 《Android Retrofit簡(jiǎn)介》
若您發(fā)現(xiàn)文章中存在錯(cuò)誤或不足的地方,希望您能指出眷蚓!