注册register
private synchronized void register(Object subscriber, boolean sticky, int priority)
register的当前对象为subscriber订阅者,一般传this
sticky 是否为粘性消息
priority 优先级
方法中通过SubscriberMethodFinder的findSubscriberMethods(subscriber.getClass())找到
onEvent
onEventMainThread
onEventBackgroundThread
onEventAsync这几个方法的Method对象。
获取到SubscriberMethod:
- final Method method;
- final ThreadMode threadMode;
- final Class
发送消息post(event)
从当前线程的ThreadLocal对象中取出PostingThreadState对象
PostingThreadState postingState = currentPostingThreadState.get();
PostingThreadState:
- List eventQueue = new ArrayList();
- boolean isPosting;
- boolean isMainThread;
- Subscription subscription;
Object event;
新的事件event会发送到对应线程的eventQueue中,
post方法中有while循环顺行发送事件postSingleEventprivate void postSingleEvent(Object event, PostingThreadState postingState)
方法中会根据event找到其所有的订阅者,并根据threadMode进行处理
处理方式:
invokeSubscriber(subscription, event)通过反射的方式进行调用
- 交给HandlerPoster,继承Handler
- 交给BackgroungPoster,实现Runnable,事件是顺行处理,线程池newCachedThreadPool
- 交给AsyncPoster,实现Runnable,事件是并行处理,线程池newCachedThreadPool