EventBus使用与解析
发布日期:2022-03-04 12:48:46 浏览次数:32 分类:技术文章

本文共 14035 字,大约阅读时间需要 46 分钟。

在编程过程中,当我们想通知其他组件某些事情发生时,我们通常使用观察者模式,正式因为观察者模式非常常见,所以在jdk1.5中已经帮助我们实现了观察者模式,我们只需要简单的继承一些类就可以快速使用观察者模式,在Android中也有一个类似功能的开源库EventBus,可以很方便的帮助我们实现观察者模式,那么我们就开始学习如何使用EventBus.

      在接下来的内容中,我首先会介绍如何使用EventBus,然后再简单的学习一下EventBus的底层实现原理,因为仅仅学习如何使用总是感觉内心不够踏实,万一哪天出了Bug也无从下手,了解了它的基本实现后,就会用得游刃有余。好了 废话不多说,下面开始学习吧

1、下载EventBus库:

EvnetBus的下载地址:https://github.com/greenrobot/EventBus.git
2、将EventBus.jar放入自己工程的libs目录即可
3、定义一个事件,这个事件一旦被EventBus分发出去就是代表某一件事情发生了,这个事件就是某个观察者关心的事情(不需要继承任何类)
4、定义观察者,然后将该观察者注册到EventBus
5、由EventBus分发事件,告知观察者某一件事情发生了
6、使用完成后从EventBus中反注册观察者。

熟悉观察者模式的朋友肯定对于上面的流程非常熟悉,其实和观察模式基本是一样的。但是也是有区别的。在观察者模式中,所有的观察者都需要实现一个接口,这个接口有一个统一的方法如:

public void onUpdate();
然后当某一个事件发生时,某个对象会调用观察者的onUpdate方法通知观察者某件事情发生了,但是在EventBus中不需要这样,EventBus中是这样实现的:
在EventBus中的观察者通常有四种订阅函数(就是某件事情发生被调用的方法)
1、onEvent
2、onEventMainThread
3、onEventBackground
4、onEventAsync
这四种订阅函数都是使用onEvent开头的,它们的功能稍有不同,在介绍不同之前先介绍两个概念:
告知观察者事件发生时通过EventBus.post函数实现,这个过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,是通过下面的订阅函数实现的。
onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEvnetBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
下面就通过一个实例来看看这几个订阅函数的使用吧
1、定义事件:

[java] 
  1. public class AsyncEvent  
  2. {  
  3.   private static final String TAG = "AsyncEvent";  
  4.   public String msg;  
  5.   public AsyncEvent(String msg)  
  6.   {  
  7.     this.msg=msg;  
  8.   }  
  9. }  

其他的事件我就不都贴出来了,我会提供代码的下载的。

2、创建观察者(也可以叫订阅者),并实现订阅方法

[java] 
  1. public class MainActivity extends Activity  
  2. {  
  3.   
  4.   @Override  
  5.   protected void onCreate(Bundle savedInstanceState)  
  6.   {  
  7.     super.onCreate(savedInstanceState);  
  8.     setContentView(R.layout.activity_main);  
  9.     //注册EventBus  
  10.     EventBus.getDefault().register(this);  
  11.   }  
  12.   
  13.   // click--------------------------------------start----------------------  
  14.    
  15.     
  16.   public void methodPost(View view)  
  17.   {  
  18.     Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  19.     EventBus.getDefault().post(new PostEvent("PostEvent"));  
  20.   }  
  21.     
  22.   public void methodMain(View view)  
  23.   {  
  24.     Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  25.     EventBus.getDefault().post(new MainEvent("MainEvent"));  
  26.   }  
  27.     
  28.   public void methodBack(View view)  
  29.   {  
  30.     Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  31.     EventBus.getDefault().post(new BackEvent("BackEvent"));  
  32.   }  
  33.     
  34.   public void methodAsync(View view)  
  35.   {  
  36.     Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  37.     EventBus.getDefault().post(new AsyncEvent("AsyncEvent"));  
  38.   }  
  39.     
  40.   public void methodSubPost(View view)  
  41.   {  
  42.     new Thread()  
  43.     {  
  44.       public void run() {  
  45.         Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  46.         EventBus.getDefault().post(new PostEvent("PostEvent"));  
  47.       };  
  48.     }.start();  
  49.      
  50.   }  
  51.     
  52.   public void methodSubMain(View view)  
  53.   {  
  54.     new Thread()  
  55.     {  
  56.       public void run() {  
  57.         Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  58.         EventBus.getDefault().post(new MainEvent("MainEvent"));  
  59.       };  
  60.     }.start();  
  61.       
  62.   }  
  63.     
  64.   public void methodSubBack(View view)  
  65.   {  
  66.     new Thread()  
  67.     {  
  68.       public void run() {  
  69.         Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  70.         EventBus.getDefault().post(new BackEvent("BackEvent"));  
  71.       };  
  72.     }.start();  
  73.      
  74.   }  
  75.     
  76.   public void methodSubAsync(View view)  
  77.   {  
  78.     new Thread()  
  79.     {  
  80.       public void run() {  
  81.         Log.d("yzy""PostThread-->"+Thread.currentThread().getId());  
  82.         EventBus.getDefault().post(new AsyncEvent("AsyncEvent"));  
  83.       };  
  84.     }.start();  
  85.      
  86.   }  
  87.     
  88.     
  89.   //click--------------------end------------------------------  
  90.     
  91.     
  92.   //Event-------------------------start-------------------------------  
  93.   /** 
  94.    * 使用onEvent来接收事件,那么接收事件和分发事件在一个线程中执行 
  95.    * @param event 
  96.    */  
  97.   public void onEvent(PostEvent event)  
  98.   {  
  99.     Log.d("yzy""OnEvent-->"+Thread.currentThread().getId());  
  100.   }  
  101.     
  102.   /** 
  103.    * 使用onEventMainThread来接收事件,那么不论分发事件在哪个线程运行,接收事件永远在UI线程执行, 
  104.    * 这对于android应用是非常有意义的 
  105.    * @param event 
  106.    */  
  107.   public void onEventMainThread(MainEvent event)  
  108.   {  
  109.     Log.d("yzy""onEventMainThread-->"+Thread.currentThread().getId());  
  110.   }  
  111.     
  112.   /** 
  113.    * 使用onEventBackgroundThread来接收事件,如果分发事件在子线程运行,那么接收事件直接在同样线程 
  114.    * 运行,如果分发事件在UI线程,那么会启动一个子线程运行接收事件 
  115.    * @param event 
  116.    */  
  117.   public void onEventBackgroundThread(BackEvent event)  
  118.   {  
  119.     Log.d("yzy""onEventBackgroundThread-->"+Thread.currentThread().getId());  
  120.   }  
  121.   /** 
  122.    * 使用onEventAsync接收事件,无论分发事件在(UI或者子线程)哪个线程执行,接收都会在另外一个子线程执行 
  123.    * @param event 
  124.    */  
  125.   public void onEventAsync(AsyncEvent event)  
  126.   {  
  127.     Log.d("yzy""onEventAsync-->"+Thread.currentThread().getId());  
  128.   }  
  129.   //Event------------------------------end-------------------------------------  
  130.   
  131.     
  132.   @Override  
  133.   protected void onDestroy()  
  134.   {  
  135.     //取消注册EventBus  
  136.     EventBus.getDefault().unregister(this);  
  137.     super.onDestroy();  
  138.   }  
  139. }  

说明:向EvnetBus中注册订阅者使用EventBus.register方法,取消订阅者使用EvnetBus.unregister方法,通知订阅者某件事情发生,调用EventBus.post方法,具体使用可以看上面的例子。在上面的例子中我创建了4中事件,并且分别中UI线程中post四个事件和在子线程中post四个事件,然后分别打印四种订阅函数所在线程的线程id.


EventBus的使用都在这里了,实在是很简单,但是如果我们在此基础上理解EvnetBus的原理,那么我们就能非常轻松的使用EventBus了。

就从EvnetBus的入口开始看吧:EventBus.register

[java] 
  1. public void register(Object subscriber) {  
  2.        register(subscriber, DEFAULT_METHOD_NAME, false0);  
  3.    }  

其实调用的就是同名函数register,它的四个参数意义分别是:

subscriber:就是要注册的一个订阅者,

methodName:就是订阅者默认的订阅函数名,其实就是“onEvent”

sticky:表示是否是粘性的,一般默认都是false,除非你调用registerSticky方法了

priority:表示事件的优先级,默认就行,

接下来我们就看看这个函数具体干了什么

[java] 
  1. private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) {  
  2.         List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),  
  3.                 methodName);  
  4.         for (SubscriberMethod subscriberMethod : subscriberMethods) {  
  5.             subscribe(subscriber, subscriberMethod, sticky, priority);  
  6.         }  
  7.     }  

通过一个findSubscriberMethods方法找到了一个订阅者中的所有订阅方法,返回一个 List<SubscriberMethod>,进入到findSubscriberMethods看看如何实现的

[java] 
  1. List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) {  
  2.         //通过订阅者类名+"."+"onEvent"创建一个key  
  3.         String key = subscriberClass.getName() + '.' + eventMethodName;  
  4.         List<SubscriberMethod> subscriberMethods;  
  5.         synchronized (methodCache) {  
  6.             //判断是否有缓存,有缓存直接返回缓存  
  7.             subscriberMethods = methodCache.get(key);  
  8.         }  
  9.         //第一次进来subscriberMethods肯定是Null  
  10.         if (subscriberMethods != null) {  
  11.             return subscriberMethods;  
  12.         }  
  13.         subscriberMethods = new ArrayList<SubscriberMethod>();  
  14.         Class<?> clazz = subscriberClass;  
  15.         HashSet<String> eventTypesFound = new HashSet<String>();  
  16.         StringBuilder methodKeyBuilder = new StringBuilder();  
  17.         while (clazz != null) {  
  18.             String name = clazz.getName();  
  19.             //过滤掉系统类  
  20.             if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {  
  21.                 // Skip system classes, this just degrades performance  
  22.                 break;  
  23.             }  
  24.   
  25.             // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)  
  26.             //通过反射,获取到订阅者的所有方法  
  27.             Method[] methods = clazz.getMethods();  
  28.             for (Method method : methods) {  
  29.                 String methodName = method.getName();  
  30.                 //只找以onEvent开头的方法  
  31.                 if (methodName.startsWith(eventMethodName)) {  
  32.                     int modifiers = method.getModifiers();  
  33.                     //判断订阅者是否是public的,并且是否有修饰符,看来订阅者只能是public的,并且不能被final,static等修饰  
  34.                     if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {  
  35.                         //获得订阅函数的参数  
  36.                         Class<?>[] parameterTypes = method.getParameterTypes();  
  37.                         //看了参数的个数只能是1个  
  38.                         if (parameterTypes.length == 1) {  
  39.                             //获取onEvent后面的部分  
  40.                             String modifierString = methodName.substring(eventMethodName.length());  
  41.                             ThreadMode threadMode;  
  42.                             if (modifierString.length() == 0) {  
  43.                                 //订阅函数为onEvnet  
  44.                                 //记录线程模型为PostThread,意义就是发布事件和接收事件在同一个线程执行,详细可以参考我对于四个订阅函数不同点分析  
  45.                                 threadMode = ThreadMode.PostThread;  
  46.                             } else if (modifierString.equals("MainThread")) {  
  47.                                 //对应onEventMainThread  
  48.                                 threadMode = ThreadMode.MainThread;  
  49.                             } else if (modifierString.equals("BackgroundThread")) {  
  50.                                 //对应onEventBackgrondThread  
  51.                                 threadMode = ThreadMode.BackgroundThread;  
  52.                             } else if (modifierString.equals("Async")) {  
  53.                                 //对应onEventAsync  
  54.                                 threadMode = ThreadMode.Async;  
  55.                             } else {  
  56.                                 if (skipMethodVerificationForClasses.containsKey(clazz)) {  
  57.                                     continue;  
  58.                                 } else {  
  59.                                     throw new EventBusException("Illegal onEvent method, check for typos: " + method);  
  60.                                 }  
  61.                             }  
  62.                             //获取参数类型,其实就是接收事件的类型  
  63.                             Class<?> eventType = parameterTypes[0];  
  64.                             methodKeyBuilder.setLength(0);  
  65.                             methodKeyBuilder.append(methodName);  
  66.                             methodKeyBuilder.append('>').append(eventType.getName());  
  67.                             String methodKey = methodKeyBuilder.toString();  
  68.                             if (eventTypesFound.add(methodKey)) {  
  69.                                 // Only add if not already found in a sub class  
  70.                                 //封装一个订阅方法对象,这个对象包含Method对象,threadMode对象,eventType对象  
  71.                                 subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));  
  72.                             }  
  73.                         }  
  74.                     } else if (!skipMethodVerificationForClasses.containsKey(clazz)) {  
  75.                         Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "."  
  76.                                 + methodName);  
  77.                     }  
  78.                 }  
  79.             }  
  80.             //看了还会遍历父类的订阅函数  
  81.             clazz = clazz.getSuperclass();  
  82.         }  
  83.         //最后加入缓存,第二次使用直接从缓存拿  
  84.         if (subscriberMethods.isEmpty()) {  
  85.             throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called "  
  86.                     + eventMethodName);  
  87.         } else {  
  88.             synchronized (methodCache) {  
  89.                 methodCache.put(key, subscriberMethods);  
  90.             }  
  91.             return subscriberMethods;  
  92.         }  
  93.     }  

对于这个方法的讲解都在注释里面了,这里就不在重复叙述了,到了这里我们就找到了一个订阅者的所有的订阅方法

我们回到register方法:

[java] 
  1. for (SubscriberMethod subscriberMethod : subscriberMethods) {  
  2.            subscribe(subscriber, subscriberMethod, sticky, priority);  
  3.        }  

对每一个订阅方法,对其调用subscribe方法,进入该方法看看到底干了什么

[java] 
  1. private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {  
  2.         subscribed = true;  
  3.         //从订阅方法中拿到订阅事件的类型  
  4.         Class<?> eventType = subscriberMethod.eventType;  
  5.         //通过订阅事件类型,找到所有的订阅(Subscription),订阅中包含了订阅者,订阅方法  
  6.         CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);  
  7.         //创建一个新的订阅  
  8.         Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);  
  9.         //将新建的订阅加入到这个事件类型对应的所有订阅列表  
  10.         if (subscriptions == null) {  
  11.             //如果该事件目前没有订阅列表,那么创建并加入该订阅  
  12.             subscriptions = new CopyOnWriteArrayList<Subscription>();  
  13.             subscriptionsByEventType.put(eventType, subscriptions);  
  14.         } else {  
  15.             //如果有订阅列表,检查是否已经加入过  
  16.             for (Subscription subscription : subscriptions) {  
  17.                 if (subscription.equals(newSubscription)) {  
  18.                     throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "  
  19.                             + eventType);  
  20.                 }  
  21.             }  
  22.         }  
  23.   
  24.         //根据优先级插入订阅  
  25.         int size = subscriptions.size();  
  26.         for (int i = 0; i <= size; i++) {  
  27.             if (i == size || newSubscription.priority > subscriptions.get(i).priority) {  
  28.                 subscriptions.add(i, newSubscription);  
  29.                 break;  
  30.             }  
  31.         }  
  32.         //将这个订阅事件加入到订阅者的订阅事件列表中  
  33.         List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);  
  34.         if (subscribedEvents == null) {  
  35.             subscribedEvents = new ArrayList<Class<?>>();  
  36.             typesBySubscriber.put(subscriber, subscribedEvents);  
  37.         }  
  38.         subscribedEvents.add(eventType);  
  39.         //这个是对粘性事件的,暂时不讨论  
  40.         if (sticky) {  
  41.             Object stickyEvent;  
  42.             synchronized (stickyEvents) {  
  43.                 stickyEvent = stickyEvents.get(eventType);  
  44.             }  
  45.             if (stickyEvent != null) {  
  46.                 postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());  
  47.             }  
  48.         }  
  49.     }  

好了,到这里差不多register方法分析完了,大致流程就是这样的,我们总结一下:

1、找到被注册者中所有的订阅方法。

2、依次遍历订阅方法,找到EventBus中eventType对应的订阅列表,然后根据当前订阅者和订阅方法创建一个新的订阅加入到订阅列表

3、找到EvnetBus中subscriber订阅的事件列表,将eventType加入到这个事件列表。


所以对于任何一个订阅者,我们可以找到它的 订阅事件类型列表,通过这个订阅事件类型,可以找到在订阅者中的订阅函数。


register分析完了就分析一下post吧,这个分析完了,EventBus的原理差不多也完了...

[java] 
  1. public void post(Object event) {  
  2.         //这个EventBus中只有一个,差不多是个单例吧,具体不用细究  
  3.         PostingThreadState postingState = currentPostingThreadState.get();  
  4.         List<Object> eventQueue = postingState.eventQueue;  
  5.         //将事件放入队列  
  6.         eventQueue.add(event);  
  7.   
  8.         if (postingState.isPosting) {  
  9.             return;  
  10.         } else {  
  11.             postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();  
  12.             postingState.isPosting = true;  
  13.             if (postingState.canceled) {  
  14.                 throw new EventBusException("Internal error. Abort state was not reset");  
  15.             }  
  16.             try {  
  17.                 while (!eventQueue.isEmpty()) {  
  18.                     //分发事件  
  19.                     postSingleEvent(eventQueue.remove(0), postingState);  
  20.                 }  
  21.             } finally {  
  22.                 postingState.isPosting = false;  
  23.                 postingState.isMainThread = false;  
  24.             }  
  25.         }  
  26.     }  

post里面没有什么具体逻辑,它的功能主要是调用postSingleEvent完成的,进入到这个函数看看吧

[java] 
  1. private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {  
  2.        Class<? extends Object> eventClass = event.getClass();  
  3.     //找到eventClass对应的事件,包含父类对应的事件和接口对应的事件  
  4.        List<Class<?>> eventTypes = findEventTypes(eventClass);  
  5.        boolean subscriptionFound = false;  
  6.        int countTypes = eventTypes.size();  
  7.        for (int h = 0; h < countTypes; h++) {  
  8.            Class<?> clazz = eventTypes.get(h);  
  9.            CopyOnWriteArrayList<Subscription> subscriptions;  
  10.            synchronized (this) {  
  11.             //找到订阅事件对应的订阅,这个是通过register加入的(还记得吗....)  
  12.                subscriptions = subscriptionsByEventType.get(clazz);  
  13.            }  
  14.            if (subscriptions != null && !subscriptions.isEmpty()) {  
  15.                for (Subscription subscription : subscriptions) {  
  16.                    postingState.event = event;  
  17.                    postingState.subscription = subscription;  
  18.                    boolean aborted = false;  
  19.                    try {  
  20.                     //对每个订阅调用该方法  
  21.                        postToSubscription(subscription, event, postingState.isMainThread);  
  22.                        aborted = postingState.canceled;  
  23.                    } finally {  
  24.                        postingState.event = null;  
  25.                        postingState.subscription = null;  
  26.                        postingState.canceled = false;  
  27.                    }  
  28.                    if (aborted) {  
  29.                        break;  
  30.                    }  
  31.                }  
  32.                subscriptionFound = true;  
  33.            }  
  34.        }  
  35.     //如果没有订阅发现,那么会Post一个NoSubscriberEvent事件  
  36.        if (!subscriptionFound) {  
  37.            Log.d(TAG, "No subscribers registered for event " + eventClass);  
  38.            if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) {  
  39.                post(new NoSubscriberEvent(this, event));  
  40.            }  
  41.        }  
  42.    }  

这个方法有个核心方法 postToSubscription方法,进入看看吧

[java] 
  1. private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {  
  2.         //第一个参数就是传入的订阅,第二个参数就是对于的分发事件,第三个参数非常关键:是否在主线程  
  3.         switch (subscription.subscriberMethod.threadMode) {  
  4.         //这个threadMode是怎么传入的,仔细想想?是不是根据onEvent,onEventMainThread,onEventBackground,onEventAsync决定的?  
  5.         case PostThread:  
  6.             //直接在本线程中调用订阅函数  
  7.             invokeSubscriber(subscription, event);  
  8.             break;  
  9.         case MainThread:  
  10.             if (isMainThread) {  
  11.                 //如果直接在主线程,那么直接在本现场中调用订阅函数  
  12.                 invokeSubscriber(subscription, event);  
  13.             } else {  
  14.                 //如果不在主线程,那么通过handler实现在主线程中执行,具体我就不跟踪了  
  15.                 mainThreadPoster.enqueue(subscription, event);  
  16.             }  
  17.             break;  
  18.         case BackgroundThread:  
  19.             if (isMainThread) {  
  20.                 //如果主线程,创建一个runnable丢入线程池中  
  21.                 backgroundPoster.enqueue(subscription, event);  
  22.             } else {  
  23.                 //如果子线程,则直接调用  
  24.                 invokeSubscriber(subscription, event);  
  25.             }  
  26.             break;  
  27.         case Async:  
  28.             //不论什么线程,直接丢入线程池  
  29.             asyncPoster.enqueue(subscription, event);  
  30.             break;  
  31.         default:  
  32.             throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);  
  33.         }  
  34.     }  

转载地址:https://blog.csdn.net/a364844763/article/details/48137459 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:运算符重载之 * ->
下一篇:讨论如何继续发展

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年03月28日 15时39分23秒