介绍
EventBus能够简化各组件间的通信,让我们的代码书写变得简单,能有效的避免发送方和接收方的耦合,能避免复杂和容易出错的依赖性和生命周期问题。
使用
添加依赖
//eventBus
compile 'org.greenrobot:eventbus:3.0.0'
在MainActivity中注册,并发送事件
public class MainActivity extends AppCompatActivity {
private Button btnMain;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMain = findViewById(R.id.btn_main);
btnMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//跳转页面
Intent intent = new Intent(MainActivity.this,EventBusActivity.class);
startActivity(intent);
}
});
//注册
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
//eventbus接收消息 指定线程
@Subscribe(threadMode = ThreadMode.MAIN)
public void receiveEvent(SimpleEvent simpleEvent){
btnMain.setText(simpleEvent.getMessage());
}
}
EventBusActivity
public class EventBusActivity extends AppCompatActivity {
private Button btnEvent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
btnEvent = findViewById(R.id.btn_main);
//注册EventBus
EventBus.getDefault().register(this);
btnEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送消息
EventBus.getDefault().post(new SimpleEvent(1,"EventActivity发送的消息"));
}
});
}
@Override
protected void onDestroy() {
//注销事件
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
事件类
public class SimpleEvent {
private int id;
private String message;
public SimpleEvent(int id,String message){
this.id = id;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
当程序启动时,点击MainActivity的按钮会启动EventBusActivity并使EventActivity注册EventBus;
点击EventBusActivity中的按钮会向MainActivity发送SimpleEvent事件,此时在MainActivity中已经指定receiveEvent()在主线程接受事件消息,得到事件并显示。
源码
那么在EventBus整个执行过程中,它做了哪些工作,我们从注册语句来看
//注册EventBus
EventBus.getDefault().register(this);
看下 EventBus.getDefault()方法:主要通过双重锁机制获取EventBus单例对象。
static volatile EventBus defaultInstance;
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
那么继续追踪,看看EventBus的构造函数干了啥:
//EventBus静态类型Builder实例
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
//主要保存某个Class的所有父类和所有接口,键为事件类型
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
//保存订阅者和订阅的方法集合,键为事件类型
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
//保存订阅事件集合,键为订阅者本身
private final Map<Object, List<Class<?>>> typesBySubscriber;
//粘性事件集合
private final Map<Class<?>, Object> stickyEvents;
//保存本地线程与订阅状态
private final ThreadLocal<PostingThreadState>
//主线程handler
private final HandlerPoster mainThreadPoster;
//后台线程Handler
private final BackgroundPoster backgroundPoster;
//异步handler
private final AsyncPoster asyncPoster;
//这是一个寻找订阅者方法的类
private final SubscriberMethodFinder subscriberMethodFinder;
//线程池执行器
private final ExecutorService executorService;
//以下几个变量都是标志位
private final boolean throwSubscriberException;
private final boolean logSubscriberExceptions;
private final boolean logNoSubscriberMessages;
private final boolean sendSubscriberExceptionEvent;
private final boolean sendNoSubscriberEvent;
private final boolean eventInheritance;
private final int indexCount;
/**
* Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
* central bus, consider {@link #getDefault()}.
*/
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
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;
}
所以以上主要是初始化EventBus类,为属性成员赋值,为后期的工作做准备。
那么让我们瞧一瞧register(this)函数干了些什么工作:
public void register(Object subscriber) {
//1.获取订阅者的类类型
Class<?> subscriberClass = subscriber.getClass();
//2.通过subscriberMethodFinder来寻找订阅者方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
//3.然后在同步代码块中执行subcribe订阅方法。
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
register方法首先①获取订阅者的类类型,
②通过subscriberMethodFinder.findSubscriberMethods来寻找订阅者方法,
③然后在同步代码块中执行subcribe订阅方法。
首先介绍一下SubscriberMethodFinder类主要是通过反射机制来获取订阅者的订阅方法,不了解反射的可以看下细说反射,Java 和 Android 开发者必须跨越的坎
那么首先我们看一下findSubscriberMethods方法到底是怎么找出订阅者方法的。
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//首先判断METHOD_CACHE是否已经含有此订阅者的所有方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//通过反射获取订阅者方法
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 {
//不为空则加入METHOD_CACHE并返回
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
那么继续查看findUsingReflection方法的实现:
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
//初始化FindState,在FIND_STATE_POOL寻找有没有可复用对象
FindState findState = prepareFindState();
//初始化findState ,对findState 变量赋值
findState.initForSubscriber(subscriberClass);
//通过反射寻找订阅者方法(包括父类),知道订阅者没有父类位置
while (findState.clazz != null) {
//反射寻找订阅者方法
findUsingReflectionInSingleClass(findState);
//给findState赋值为findState的父类;
findState.moveToSuperclass();
}
//释放资源并返回订阅方法
return getMethodsAndRelease(findState);
}
这里主要通过while循环将订阅者和订阅者的所有父类的订阅方法都找出来,那么具体看一下寻找订阅方法具体实现:
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 modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
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()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
首先通过Class.getDeclaredMethods方法获取所有的类方法;如果抛出异常则使用Class.getMethods方法获取所有方法。Class类中getMethods() 与getDeclaredMethods() 方法的区别
然后遍历所有方法,找出符合条件的方法:
①获取当前方法的修饰符,如果此方法是public且不是abstract、static等等类型,那么就获取它的方法参数,得到参数列表;
②若参数长度等于1,就获取此方法的Subscribe注解对应的值;不熟悉注解的戳这里秒懂,Java 注解 (Annotation)你可以这样学
③判断注解对象是否为空,若不为空,则判断此eventType和method是否合法;若合法,则添加到findState.subscriberMethods集合中保存。
言归正传findSubscriberMethods()最终返回了SubscriberMethod的集合,SubscriberMethod类属性成员
//订阅方法
final Method method;
//线程模式
final ThreadMode threadMode;
//事件类型
final Class<?> eventType;
//优先级
final int priority;
//是否为粘性事件
final boolean sticky;
//订阅方法名
String methodString;
接下来回到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);
}
}
}
在register同步代码块当中,遍历当前订阅者的所有订阅方法,执行订阅函数。
// 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) {
//必须考虑事件类型的所有子类的现有粘性事件。
//Note:在许多棘手事件中迭代所有事件可能是低效的,
//因此应该改变数据结构以允许更有效的查找。
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);
}
}
}
让我们回头看一下MainActivity
EventBus.getDefault().register(this);
@Subscribe(threadMode = ThreadMode.MAIN)
public void receiveEvent(SimpleEvent simpleEvent){
btnMain.setText(simpleEvent.getMessage());
}
至此,以上两句代码执行完毕。
接下来,让我们看一看EventBus做了哪些事情:
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();
List<Object> eventQueue = postingState.eventQueue;
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 {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
post()方法首先执行currentPostingThreadState.get()方法,获取PostingThreadState对象。
首先currentPostingThreadState初始化就保存了一个当前的PostingThreadState对象,通过currentPostingThreadState.get()获取对象实例,那么PostingThreadState对象具体有哪些属性?
/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
PostingThreadState中保存的是即将要发送的订阅事件信息。
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
然后将订阅事件加入队列中,然后判断此事件是否已经被发送、判断当前是否为主线程,然后若队列不为空,则一直发送订阅事件,最后将标志还原。
那么postSingleEvent()是如何向订阅线程发送消息?
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
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) {
Log.d(TAG, "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 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);
}
}
首先判断订阅方法指定的threadMode:即在哪个线程执行订阅方法。
①POSTING:直接在房前线程执行,即在post方法线程执行此事件;
②MAIN:不论post在哪个线程,订阅事件在主线程执行;
③BACKGROUND:后台线程执行,即子线程执行;
④ASYNC:另起线程执行订阅事件;
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);
}
}
invokeSubscriber方法直接利用反射机制调用此方法,完成消息的通讯;
至此EventBus消息通讯到此结束,那么我们回头看下,夸线程通讯是怎么实现的呢?
首先看一下以下两句代码如何执行发送消息的操作。
private final HandlerPoster mainThreadPoster;
mainThreadPoster.enqueue(subscription, event);
HandlerPoster类:
final class HandlerPoster extends Handler {
private final PendingPostQueue queue;
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.eventBus = eventBus;
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
queue = new PendingPostQueue();
}
void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
}
HandlerPoster最终是通过Handler机制执行订阅消息的执行;
那么BackgroundPsoter是通过什么机制执行的呢?
final class BackgroundPoster implements Runnable {
private final PendingPostQueue queue;
private final EventBus eventBus;
private volatile boolean executorRunning;
BackgroundPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
eventBus.getExecutorService().execute(this);
}
}
}
@Override
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
}
有以上代码来看,BackgroundPoster是通过线程池执行的;
同理AsyncPoster:
class AsyncPoster implements Runnable {
private final PendingPostQueue queue;
private final EventBus eventBus;
AsyncPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
}
发现AsyncPoster就执行了当前的订阅事件,即单个事件。
网友评论