分析:
1>:首先根据 subscriberMethod.eventType,在 subscriptionsByEventType 中查找 CopyOnWriteArrayList<Subscription>,没有就创建;
subscriptionsByEventType 是一个Map集合,用于存储 EventBus 所有的方法,
key: eventType,value: CopyOnWriteArrayList<Subscription>;
2>:然后把 传入的 参数 封装成 Subscription(subscriber, subscriberMethod, priority) 对象;
3>:然后添加 上边的对象 newSubscription ,根据 优先级 添加到 list集合
register结论:扫描该类中所有的方法,把匹配的方法保存到subscriptionsByEventType(Map,key:eventType,value:CopyOnWriteArrayList<Subscription>)
eventType:就是post(Javabean)数据类型,
Subscription保存了 subscriber、subscriberMethod(method,threadMode,eventType,priority,sticky)
2. post
register:把所有方法存储到subscriptionsByEventType,post就是从该Map集合中取方法,然后调用
public void post(Object event) {
// currentPostingThreadState:ThreadLocal类型的,里边存储的 PostingThreadState
// PostingThreadState 包含:eventQueue队列 和 一些标志位
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
// eventQueue队列:用于保存 post 传入的event,其实就是 post传入过来的 javabean数据
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 {
// 遍历队列中存储的所有的 event,调用 下边的方法,
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
// currentPostingThreadState 是 ThreadLocal 类型的,用于存储 PostingThreadState
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
final static class PostingThreadState {
// eventQueue
final List<Object> eventQueue = new ArrayList<Object>();
// 下边是一些标志位
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
} |