EventBus原理詳解

2021-08-26 15:09:03 字數 2644 閱讀 8792

在eventbus 3.0 使用介紹 這篇部落格中介紹了關於eventbus的一些使用方法,下面我們就來看看它內部的具體實現吧!

通過上面的幾張圖,我們可以大致了解eventbus的工作流程,下面我們在來介紹一下這個流程中比較重要的幾個方法

listfindsubscribermethods(class> subscriberclass) 

if (ignoregeneratedindex) else

if (subscribermethods.isempty()) else

}

通過反射獲取方法

//準備乙個findstate 來裝訂閱者的方法

private findstate preparefindstate() }}

return new findstate();

}

//將findstate 裡面的方法放入subscribermethods list中,並將findstate 放回去繼續使用

private listgetmethodsandrelease(findstate findstate) }}

return subscribermethods;

}

private void findusingreflectioninsingleclass(findstate findstate)  catch (throwable th) 

for (method method : methods)

}} else if (strictmethodverification && method.isannotationpresent(subscribe.class))

} else if (strictmethodverification && method.isannotationpresent(subscribe.class)) }}

通過apt的到方法

private listfindusinginfo(class> subscriberclass) 

}} else

findstate.movetosuperclass();

}return getmethodsandrelease(findstate);

}

private subscriberinfo getsubscriberinfo(findstate findstate) 

}if (subscriberinfoindexes != null) }}

return null;

}

private void subscribe(object subscriber, subscribermethod subscribermethod)  else 

}int size = subscriptions.size();

for (int i = 0; i <= size; i++)

}list> subscribedevents = typesbysubscriber.get(subscriber);

if (subscribedevents == null)

subscribedevents.add(eventtype);

if (subscribermethod.sticky)

}} else }}

//通過threadmode來確認使用哪個執行緒執行訂閱者的訂閱函式

private void posttosubscription(subscription subscription, object event, boolean ismainthread) else

break;

case background:

if (ismainthread) else

break;

case async:

asyncposter.enqueue(subscription, event);

break;

default:

throw new illegalstateexception("unknown thread mode: " + subscription.subscribermethod.threadmode);}}

其中mainthreadposter繼承自handler、backgroundposter和asyncposter都繼承自runnabl

EventBus設計原理 流程分析

本篇不涉及任何原始碼,單純講一下它的流程,然後講一下優缺點。eventbus 中有三個集合,這基本就是核心所在。private final map,copyonwritearraylist subscriptionsbyeventtype 第乙個集合的儲存的 key是資料型別的clazz value...

EventBus二之反射原理

目錄 1 新建android libray 2 定義eventbus反射機制需要的元素 3 實現eventbus核心類 新建android libray 定義eventbus反射機制需要的元素 a.新增註解類 target elementtype.method retention retention...

事件匯流排 EventBus的設計原理

為什麼要設計eventbus?因為他是領域驅動設計中比不可少的模組,它承擔傳輸資料的作用,它可以解耦模組之間的耦合性。如何對eventsbus進行定義 1 eventbus是基於jvm內部的資料傳輸系統,不是jms。2 eventbus的核心物件為event和eventhandler。eventbu...