EventBus采用的是订阅者模式,订阅者和发布者都可以有任意个,他们的联系是参数类型,所有订阅者的能和发布者对应的全部方法都会被执行
使用方式如下
EventBus.getDefault().register(this);
EventBus.getDefault().post(new TestEvent("本大爷调用了"));
首先调用register()订阅,然后使用post()发布
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
public EventBus() {
this(DEFAULT_BUILDER);
}
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
简单的单利模式,通过无参构造方法,调用有参构造方法,传入一个默认的builder对象,最后还是通过建造者模式初始化一些参数,并获取对象;
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();//这里拿到注册的class
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//获取注册的class的全部方法
synchronized (this) {
//遍历全部方法,并加入订阅集合中
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
//subscribe实现
// 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) {
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);
}
}
}
register的参数传入的this,不是指的上下文(context),而是指的代码所在的类(class)。
通过反射,拿到订阅者类的全部方法,把订阅者和方法封装到Subscription,并放到集合中
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(TestEvent event){
TextView textView=findViewById(R.id.test_text);
textView.setText(event.getMsg());
}
集合是根据这里onEvent()参数类型所建立的,然后根据参数类型放到Map里,所有的类型也放到一个数组里
下面分析发布者代码:
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
/** Posts the given event to the event bus. */
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();//拿到一个线程安全的PostingThreadState 实例
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;
}
}
}
这里用了一个线程安全的PostingThreadState 来保存发布状态,需要发布的消息储存在一个队列里,通过队列来发布消息
下面来分析一下发布的实现:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;//发布结果
//是不是继承,理解为,是不是处理父类和实现的接口,通过builder设置值,默认未true
if (eventInheritance) {
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);
}
//处理一下发布失败的结果
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));
}
}
}
这里可以看出,通过事件类型来发布,是不是处理父类,封装倒了builder里,可以通过builder设置默认是true
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;
}
这里拿到订阅者和发布者,将两者放到同哟个方法中处理,同时改变发布状态并返回发布结果:有订阅者则返回成功,否则认定为失败
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);
}
}
这里根据线程处理发布,通过hadler来处理
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);
}
}
Method.invoke();执行订阅者的方法,将发布者作为参数传入。结束。。。。。。