前言
由於最近項目中頻繁使用EventBus,所以想了解下它內部原理,我們得"知其然知其所以然"。在這裏總結一下,方便自己複習。
歡迎start我的GitHub項目,裏面會不定時更細Android 、java、設計模式相關知識!
EventBus的使用
項目配置
很簡單只需要在build.gradle(app)
下添加如下:
implementation 'org.greenrobot:eventbus:3.1.1'
項目中使用
普通使用:
1、發送消息:
EventBus.getDefault().post(事件);
2、在接受頁面註冊和反註冊,並接收。
//註冊
EventBus.getDefault().register(this);
//反註冊
EventBus.getDefault().unregister(this);
//接收事件(getdata這名字是隨便的,起什麼都可以)
@Subscribe(threadMode = ThreadMode.MAIN)
public void getdata(事件) {
//在這裏處理髮送的事件
}
普通使用例子:
比如現在有這樣一個需求,有兩個頁面分別是MainActivity
和Main2Activity
。需要MainActivity
跳轉到Main2Activity
,點擊Main2Activity
中的按鈕返回並攜帶數據。(當然我們也可以使用onActivityResult
去實現 -。-)
MainActivity
代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//註冊
EventBus.getDefault().register(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.main_tv:
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
break;
}
}
//訂閱者方法
@Subscribe(threadMode = ThreadMode.MAIN)
public void getdata(Message message) {
Toast.makeText(this, "Type=" + message.getType(), Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
//反註冊
EventBus.getDefault().unregister(this);
}
}
Main2Activity
代碼:
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void onClick2(View view) {
//發送消息
EventBus.getDefault().post(new Message(1));
finish();
}
}
Message
事件實體:
public class Message {
private int type;
public Message(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
效果圖
可能有人會說,官網的是在onStart()/onStop()中註冊和反註冊,你怎麼在onCreate方法中註冊,在onDestory方法中反註冊?這樣的話有一些情況我們普通的方式去發送事件,是在需要接收消息頁面會收不到,因爲使用時需要往已經註冊的頁面發送消息,才能接受到。當我們發送消息時註冊方法還沒有被調用和關聯訂閱者,那麼就無法接受事件。
粘性事件使用:
1、發送消息:
EventBus.getDefault().postSticky(事件);
2、在接受頁面註冊和反註冊,並接收。
//註冊
EventBus.getDefault().register(this);
//反註冊
EventBus.getDefault().unregister(this);
//接收事件(getdata這名字是隨便的,起什麼都可以)
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void getdata(事件) {
//在這裏處理髮送的事件
}
粘性事件例子;
有這樣的一個需求,在MainActivity往Main2Activity(沒有創建過)頁面傳遞數據(當然我們也可以使用Intent攜帶Bundle傳遞)。
MainActivity
代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.main_tv:
//發送消息
EventBus.getDefault().postSticky(new Message(1));
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
break;
}
}
}
Main2Activity
代碼:
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
@Override
protected void onStart() {
super.onStart();
//註冊
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
super.onStop();
//反註冊
EventBus.getDefault().unregister(this);
}
public void onClick2(View view) {
finish();
}
//訂閱者方法
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void getdata(Message message) {
Toast.makeText(this, "MainActivity發送Type爲" + message.getType(), Toast.LENGTH_SHORT).show();
}
}
效果圖
EventBus源碼分析:
EventBus.getDefault()分析
我們在使用時不管操作什麼都需要調用EventBus.getDefault()
方法。
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
我們看上面源碼可知,它用到了雙重檢鎖獲取到了EventBus的對象。
register註冊分析
public void register(Object subscriber) {
//獲取註冊的對象
Class<?> subscriberClass = subscriber.getClass();
//找到訂閱方法集合
List<SubscriberMethod>subscriberMethods=subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
//訂閱
subscribe(subscriber, subscriberMethod);
}
}
}
解析1SubscriberMethod
是存儲訂閱方法信息:
public class SubscriberMethod {
final Method method;
final ThreadMode threadMode;
final Class<?> eventType;
final int priority;
final boolean sticky;
/** Used for efficient comparison */
String methodString;
......
}
ThreadMode
訂閱者線程
eventType
事件
priority
優先級
sticky
是否粘性事件
Method
接受事件的方法(比如例子中的getdata()
)
解析2findSubscriberMethods
查找訂閱者方法
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE=new ConcurrentHashMap<>();
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//通過訂閱者對象查找緩存(以ConcurrentHashMap存儲的key爲訂閱者的類,value爲訂閱者方法集合)
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
//查到的緩存不爲空直接返回
if (subscriberMethods != null) {
return subscriberMethods;
}
//是否忽略生成的索引 ,默認false
if (ignoreGeneratedIndex) {
//以反射的方式獲取訂閱者訂閱方法
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//以索引的形式獲取
subscriberMethods = findUsingInfo(subscriberClass);
}
//判斷內容是否爲空,爲空拋異常
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass + " and its super classes have no public methods with the @Subscribe annotation");
} else {
//緩存到ConcurrentHashMap中,以便於下次查找
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
解析2.1findUsingReflection
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
//創建FindState對象
FindState findState = prepareFindState();
//於訂閱者類關聯
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//使用反射獲取訂閱方法
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
//返回FindState中的訂閱方法集合
return getMethodsAndRelease(findState);
}
解析2.1.1findUsingReflectionInSingleClass
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
//獲取本類中的所有方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
//獲取本類和父類的所有公共方法
methods = findState.clazz.getMethods();
//設置標記
findState.skipSuperClasses = true;
}
//遍歷
for (Method method : methods) {
//返回方法的int值
int modifiers = method.getModifiers();
//忽略不是PUBLIC和static
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//獲取參數類型
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
//獲取Subscribe註解(裏面有線程模型、是否粘性、優先級)
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
//獲取線程模型
ThreadMode threadMode = subscribeAnnotation.threadMode();
//添加到訂閱者集合
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
......
}
解析2.2findUsingInfo
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//第一次會爲空
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 {
//調用解析2.1.1反射獲取
findUsingReflectionInSingleClass(findState);
}
//在父類中查找
findState.moveToSuperclass();
}
//返回訂閱者集合
return getMethodsAndRelease(findState);
}
解析3subscribe
private final Map<Class<?>,CopyOnWriteArrayList<Subscription>>=subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
// Must be called in synchronized block
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);
}
}
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;
}
}
//獲取當前訂閱者的事件
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
//爲空創建並添加緩存中
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
//添加當前事件
subscribedEvents.add(eventType);
//是否是粘性事件
if (subscriberMethod.sticky) {
//默認true
if (eventInheritance) {
// 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>).
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);
//發送事件
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
註冊總結
註冊時發送事件checkPostStickyEventToSubscription
會調用這個方法postSingleEventForEventType
post普通發送分析
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
使用ThreadLocal
存儲PostingThreadState
,線程安全的
/** For ThreadLocal, much faster to set (and get multiple values). */
fin al static class PostingThreadState {
//事件隊列集合
final List<Object> eventQueue = new ArrayList<>();
//是否發送
boolean isPosting;
//是否是主線程
boolean isMainThread;
//存儲訂閱信息的
Subscription subscription;
//事件
Object event;
//是否取消
boolean canceled;
}
/** 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) {
//是否是主線程
postingState.isMainThread = isMainThread();
//更改是否發送過默認值
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 {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//默認值爲true
if (eventInheritance) {
//查找事件所有Class對象,包括超類和接口內部使用hashmap緩存
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);
}
//subscriptionFound爲true是調用 也就是 subscriptions爲空或者size爲0時
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
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 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);
}
}
1、PostThread 默認的線程模式,直接調用invokeSubscriber
方法。
發佈事件和接收事件在同一個線程
2、MAIN判斷是否在主線程,true直接調用invokeSubscriber
方法,false使用mainThreadPoster
處理,他的視線類是HandlerPoster
。加入隊列使用handler發送消息在handler的handleMessage中去執行invokeSubscriber
方法。
事件的處理會在UI線程中執行
3、MAIN_ORDERED先判斷mainThreadPoster
是否爲空,true調用mainThreadPoster
排隊等待傳遞非阻塞的,否則直接調用invokeSubscriber
方法。
事件的處理會在UI線程中執行
4、BACKGROUND判斷是否在主線程,true使用BackgroundPoster處理,false直接調用invokeSubscriber
事件是在UI線程中發佈出來的,那麼該事件處理函數就會在新的線程中運行,如果事件本來就是子線程中發佈出來的,那麼該事件處理函數直接在發佈事件的線程中執行
5、ASYNC直接交由AsyncPoster
處理
事件處理函數都會在新建的子線程中執行
invokeSubscriber
通過反射調用訂閱方法
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);
}
}
postSticky粘性事件
private final Map<Class<?>, Object> stickyEvents;
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);
}
先同步,緩存到stickyEvents
(ConcurrentHashMap緩存的),之後調用post方法。之後流程跟普通發送事件一樣。
unregister 反註冊分析
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
//獲取訂閱者集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍歷
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//移除訂閱者
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
unsubscribeByEventType
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//獲取訂閱者信息集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
//遍歷
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
//判斷是否是當前訂閱者
if (subscription.subscriber == subscriber) {
subscription.active = false;
//移除
subscriptions.remove(i);
i--;
size--;
}
}
}
}