Exemplo n.º 1
0
 /**
  * postToSubscription 函数中会判断订阅者的 ThreadMode,从而决定在什么 Mode 下执行事件响应函数。
  *
  * <p>1、PostThread:默认的 ThreadMode,表示在执行 Post 操作的线程直接调用订阅者的事件响应方法,不论该线程是否为主线程(UI
  * 线程)。当该线程为主线程时,响应方法中不能有耗时操作,否则有卡主线程的风险。适用场景:对于是否在主线程执行无要求,但若 Post 线程为主线程,不能耗时的操作;
  * 2、MainThread:在主线程中执行响应方法。如果发布线程就是主线程,则直接调用订阅者的事件响应方法,否则通过主线程的 Handler
  * 发送消息在主线程中处理——调用订阅者的事件响应函数。显然,MainThread类的方法也不能有耗时操作,以避免卡主线程。适用场景:必须在主线程执行的操作;
  * 3、BackgroundThread:在后台线程中执行响应方法。如果发布线程不是主线程,则直接调用订阅者的事件响应函数,否则启动唯一的后台线程去处理。由于后台线程是唯一的,当事件超过一个的时候,它们会被放在队列中依次执行,因此该类响应方法虽然没有PostThread类和MainThread类方法对性能敏感,但最好不要有重度耗时的操作或太频繁的轻度耗时操作,以造成其他操作等待。适用场景:操作轻微耗时且不会过于频繁,即一般的耗时操作都可以放在这里;
  * 4、Async:不论发布线程是否为主线程,都使用一个空闲线程来处理。和BackgroundThread不同的是,Async类的所有线程是相互独立的,因此不会出现卡线程的问题。适用场景:长耗时操作,例如网络访问。
  *
  * @param subscription
  * @param event
  * @param isMainThread
  */
 private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
   switch (subscription.subscriberMethod.threadMode) {
     case PostThread:
       invokeSubscriber(subscription, event);
       break;
     case MainThread: // 在主线程中执行响应方法
       if (isMainThread) { // 如果发布线程就是主线程,则直接调用订阅者的事件响应方法
         invokeSubscriber(subscription, event);
       } else { // 否则通过主线程的 Handler 发送消息在主线程中处理——调用订阅者的事件响应函数
         mainThreadPoster.enqueue(subscription, event);
       }
       break;
     case BackgroundThread: // 在后台线程中执行响应方法
       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);
   }
 }
Exemplo n.º 2
0
 /**
  * Invokes the subscriber if the subscriptions is still active. Skipping subscriptions prevents
  * race conditions between {@link #unregister(Object)} and event delivery. Otherwise the event
  * might be delivered after the subscriber unregistered. This is particularly important for main
  * thread delivery and registrations bound to the live cycle of an Activity or Fragment.
  *
  * <p>调用订阅者响应相关事件,前提是active状态为true
  */
 void invokeSubscriber(PendingPost pendingPost) {
   Object event = pendingPost.event;
   Subscription subscription = pendingPost.subscription;
   PendingPost.releasePendingPost(pendingPost);
   if (subscription.active) {
     invokeSubscriber(subscription, event);
   }
 }