Androidイベントバス:EventBus

17433 ワード

最近別のプロジェクトを維持して、各種のライブラリはすべて比較的に古くて、eventbusは2.xバージョンを使って、そこで1つのアップグレードに来て、ついでにeventbusのソースコードを読んで、ここでメモをします:
EventBus 2.xアップグレード3.x
2.xと3.xの対応関係:
onEvent--  ThreadMode.POSTING;
onEventMainThread--  ThreadMode.MAIN
onEventAsync--  ThreadMode.BACKGROUND
onEventBackgroundThread--  ThreadMode.ASYNC

1.パッケージ名の置換
Eventbusがアップグレードされた後、パッケージ名が変更され、ctrl+shift+rグローバルに置き換えることができます.また、studioに自動インポートパッケージ名を設定してimport de.greenrobot.event.EventBusを設定することもできます.import org.greenrobot.eventbus.EventBusに置き換えます.すべて置換
2.方法は注記方式を使用する必要がある
ctrl+shift+fグローバル検索では、上記の4つの注釈方法が順次追加されます.例えば、onEvent方法について、「public void onEvent(」@Subscribe(threadMode=ThreadMode.POSTING)」3.EventBus 3.0バージョンを検索するとregisterStickyが削除され、各メソッドの注釈にsticky=true.検索「.registerSticky(」.,registerStickyをregisterに置き換え,クラスのメソッド注記にstickyを追加する.
EventBusソースの解読:
1.EventBusの構築方法
/** 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の構造方法を見てみましょう.
...
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
...
public EventBus() {
    this(DEFAULT_BUILDER);
}


これはeventbusのもう一つの構築方法を呼び出しました.
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;
}

ここではコンストラクタモードを採用し、EventbusBuilderを構築することでEventbusを構成します.
2.登録購読
Eventbusを取得すると、購読者をEventbusに登録できます.登録方法は次のとおりです.
public void register(Object subscriber) {
    Class> subscriberClass = subscriber.getClass();
    //     (    subscriber)          
    List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        //        ,    
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

1)購読者の購読方法の検索
登録方法としては、①サブスクライバ内のすべてのサブスクライバメソッドを検索すること、②サブスクライバの登録を行うことが2つあります.SubscriberMethodクラスは、主にサブスクライバメソッドMethodオブジェクト、スレッドモード、イベントタイプ、優先度(priority)、スティッキーイベント(sticky)などを保存するために使用されます.findSubscriberMethodsは、次のようになります.
List findSubscriberMethods(Class> subscriberClass) {
    //        
    List subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    ```
    //            MyEventBusIndex(  http://greenrobot.org/eventbus/documentation/subscriber-index/)
    //  false,    EventbusBuilder   。            findUsingInfo           
    ```
    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.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}


次にfindUsingInfoメソッドを見てみましょう.
private List findUsingInfo(Class> subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //       
        findState.subscriberInfo = getSubscriberInfo(findState);
        //      EventBuilder   MyEventBusIndex,     subscriberInfo
        if (findState.subscriberInfo != null) {
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
            //    EventBuilder  MyEventBusIndex,             findState,      ,    
        } else {
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    // findState     ,          
    return getMethodsAndRelease(findState);
}

moreはMyEventBusIndexを構成していません.次にfindUsingReflectionInSingleClassメソッドを見てみましょう.
private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        //               ,     getMethods() ,           Activity
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }
    for (Method method : methods) {
        //        ,eg. public
        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 
                        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");
        }
    }
}

これで、購読者を検索する購読方法は終了します.
2)購読者の登録プロセス
サブスクライバのサブスクライバメソッドを検索した後、再すべてのサブスクライバメソッドの登録を開始し、registerメソッドに戻り、subscribeメソッドを呼び出します.
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //           
    Class> eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //  eventType        ,         
    CopyOnWriteArrayList 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> 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).
            Set, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry, 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);
        }
    }
}

subscribeは主に2つのことを行い,1 SubscriiptionをevntTypeに従ってsubscriptionsByEventTypeにカプセル化し,subscribedEventsをsubscriberに従ってtypeBySubscriberにカプセル化する,2粘性イベントの処理を行った.
3.イベント送信
Eventbusオブジェクトを取得した後、postメソッドでイベントの送信を完了します.
/** Posts the given event to the event bus. */
public void post(Object event) {
    //PostingThreadState        (eventQueue)       (isPosting,isMainThread,subscription,event,canceled)
    PostingThreadState postingState = currentPostingThreadState.get();
    //      ,            
    List 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;
        }
    }
}

postSingleEventが何をしたか見てみましょう.
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //        ,  true,    EventBusBuilder  
    if (eventInheritance) {
        //        
        List> 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));
        }
    }
}

イベントはpostSingleEventForEventTypeメソッドで処理されます.
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class> eventClass) {
    CopyOnWriteArrayList subscriptions;
    synchronized (this) {
        //             
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        //   event    Subscription(    )   postingState,    postToSubscription         
        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 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);
    }
}

サブスクリプション方法のスレッドパターンによって、それぞれ処理され、Mainであれば、コミットされたスレッドがメインスレッドであれば、サブスクリプションを直接実行する方法を反射することによって、メインスレッドでなければ、mainThreadPosterが私たちのサブスクリプションイベントをメインスレッドキューに追加する必要があります.mainThreadPosterはHandlerから継承され、Handlerによってサブスクリプション方法をメインスレッドに切り替えます.これで、イベントは送信されます送りが終わる.
4.購読者登録を取り消す
登録解除はEventbusオブジェクトを取得した後、unregieterメソッドを呼び出します.
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
    List> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        typesBySubscriber.remove(subscriber);
    } else {
        logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object 
typesBySubscriber   map  ,         。   subscriber  subscribedTypes  ,   subscriber   eventTpye typesBySubscriber   。  subscribedTypes   unsubscribeByEventType  :
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class> eventType) {
    List subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        for (int i = 0; i < size; i++) {
            Subscription subscription = subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                i--;
                size--;
            }
        }
    }
}

SubscriptionsからSubscriptionsを削除し、購読解除を完了します.
参考資料:1.https://www.jianshu.com/p/e28e1692d0c7 2.https://github.com/greenrobot/EventBus 3.「Android進級の光」(劉望舒)第七章