【Android】EventBus的使用及源码分析

news2025/3/18 12:40:10

文章目录

  • 介绍
    • 优点
    • 基本用法
    • 线程模式
      • POSTING
      • MAIN
      • MAIN_ORDERED
      • BACKGROUND
      • ASYNC
    • 黏性事件
  • 源码
    • 注册
      • getDefault()
      • register
      • findSubscriberMethods
      • 小结
    • post
    • postSticky
    • unregister

介绍

img

优点

  • 简化组件之间的通信
    • 解耦事件发送者和接收者
    • 在 Activity、Fragment 和后台线程中表现良好
    • 避免复杂且容易出错的依赖关系和生命周期问题
  • 让你的代码更简单
  • 很快,很小
  • 具有高级功能,如交付线程、订阅者优先级等。

基本用法

导入依赖

implementation "org.greenrobot:eventbus:3.3.1"
  1. 定义事件:
public static class MessageEvent { /* Additional fields if needed */ }
  1. 准备订阅者:声明并注释您的订阅方法,可以选择指定线程模式

    @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onMessageEvent(MessageEvent event) {
        // Do something
    }
    

    注册和取消注册您的订户。例如在 Android 上,活动和片段通常应根据其生命周期进行注册:

     @Override
     public void onStart() {
         super.onStart();
         EventBus.getDefault().register(this);
     }
    
     @Override
     public void onStop() {
         super.onStop();
         EventBus.getDefault().unregister(this);
     }
    
  2. 发布活动:

 EventBus.getDefault().post(new MessageEvent());

线程模式

POSTING

  • 特点:订阅者在发布事件的同一线程中被调用。
  • 优点:开销最小,避免了线程切换。
  • 适用场景:已知任务简单且快速完成,不依赖主线程。
  • 注意:长时间任务可能阻塞发布线程(如是主线程,会导致UI卡顿)。
@Subscribe(threadMode = ThreadMode.POSTING)
public void onMessage(MessageEvent event) {
    log(event.message); // 快速返回的简单任务
}

MAIN

  • 特点:

    • 订阅者在主线程(UI线程)中被调用
    • 如果发布线程为主线程,则同步调用(与 POSTING 类似)
  • 适用场景:UI更新或需要在主线程完成的轻量任务。

  • 注意:避免执行耗时任务,否则会阻塞主线程,导致卡顿。

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(MessageEvent event) {
    textView.setText(event.message); // 更新UI
}

MAIN_ORDERED

  • 特点:
    1. 在主线程中执行。
    2. 按顺序执行:事件会一个接一个地处理,不会乱序。
  • 适用场景:依赖特定执行顺序的UI更新逻辑。
  • 注意:与 MAIN 类似,避免耗时任务,确保任务快速返回。
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onMessageEvent(String event) {
    Log.d("EventBus", "Event received: " + event); // 按顺序更新UI
}

BACKGROUND

  • 特点:
    • 如果发布线程为主线程,事件处理方法会切换到后台线程。
    • 如果发布线程是非主线程,事件处理方法直接在发布线程中执行。
  • 适用场景:后台任务,如数据库存储、文件操作。
  • 注意:快速返回,避免阻塞后台线程。
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event) {
    saveToDisk(event.message); // 后台存储操作
}

ASYNC

  • 特点:事件处理程序始终在独立线程中调用,与发布线程或主线程完全分离。
  • 适用场景:耗时操作,如网络请求、复杂计算。
  • 注意:避免触发大量异步任务,防止线程池耗尽资源。
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessage(MessageEvent event) {
    backend.send(event.message); // 异步网络请求
}

黏性事件

发送事件之后再订阅也能收到该事件

@Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
public void onMessageEvent(MessageEvent messageEvent) {
    tv.setText(messageEvent.getMessage());
}
EventBus.getDefault().postSticky(new MessageEvent("SecondActivity的信息"));

源码

注册

getDefault()

public class EventBus {

    // 静态变量,存储唯一的 EventBus 实例
    // 使用 volatile 关键字,确保多线程环境下变量的可见性和防止指令重排
    static volatile EventBus defaultInstance;

    public static EventBus getDefault() {
        // 将静态变量 defaultInstance 赋值给局部变量 instance,减少对主内存的访问
        EventBus instance = defaultInstance;

        // 第一次检查,避免不必要的同步开销
        if (instance == null) {
            // 如果实例未被初始化,进入同步块
            synchronized (EventBus.class) {
                // 再次将 defaultInstance 的值赋给 instance(看这个时候defaultInstance为不为空)
                instance = EventBus.defaultInstance;

                // 第二次检查,确保实例仍未被初始化(双重检查锁定)
                if (instance == null) {
                    // 创建新的 EventBus 实例并赋值给 defaultInstance 和局部变量 instance
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
    }
}
public EventBus() {
    this(DEFAULT_BUILDER);
}
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
EventBus(EventBusBuilder builder) {
    //日志
    logger = builder.getLogger();
    //这个集合可以根据事件类型获取订阅者
    //key:事件类型,value:订阅该事件的订阅者集合
    subscriptionsByEventType = new HashMap<>();
    //订阅者所订阅的事件集合
    //key:订阅者,value:该订阅者订阅的事件集合
    typesBySubscriber = new HashMap<>();
    //粘性事件集合
    //key:事件Class对象,value:事件对象
    stickyEvents = new ConcurrentHashMap<>();
    //Android主线程处理事件
    mainThreadSupport = builder.getMainThreadSupport();
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
    //Background事件发送者
    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对象,在创建EventBus时最终会调用它的有参构造函数,传入一个EventBus.Builder对象。在这个有参构造函数内部对属性进行初始化

register

public class EventBus {
    public void register(Object subscriber) {
        // 1、通过反射获取到订阅者的Class对象
        Class<?> subscriberClass = subscriber.getClass();
        // 2、通过subscriberMethodFinder对象获取订阅者所订阅事件的集合
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            // 3、遍历集合进行注册
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 4、获取事件类型
        Class<?> eventType = subscriberMethod.eventType;
        // 5、封装Subscription对象
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // 6、通过事件类型获取该事件的订阅者集合
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        // 7、如果没有订阅者订阅该事件
        if (subscriptions == null) {
            // 创建集合,存入subscriptionsByEventType集合中
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else { // 8、如果有订阅者已经订阅了该事件
            // 判断这些订阅者中是否有重复订阅的现象
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                                            + eventType);
            }
        }
        int size = subscriptions.size();
        // 9、遍历该事件的所有订阅者
        for (int i = 0; i <= size; i++) {
            // 按照优先级高低进行插入,如果优先级最低,插入到集合尾部
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        // 10、获取该事件订阅者订阅的所有事件集合
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        // 11、将该事件加入到集合中
        subscribedEvents.add(eventType);

        // 12、判断该事件是否是粘性事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) { // 13、判断事件的继承性,默认是不可继承
                // 14、获取所有粘性事件并遍历,判断继承关系
                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();
                        // 15、调用checkPostStickyEventToSubscription方法
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

    private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            // 16、如果粘性事件不为空
            postToSubscription(newSubscription, stickyEvent, isMainThread());
        }
    }


    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        // 17、根据threadMode的类型去选择是直接反射调用方法,还是将事件插入队列
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    // 18、通过反射的方式调用
                    invokeSubscriber(subscription, event);
                } else {
                    // 19、将粘性事件插入到队列中
                    // 最后还是会调用EventBus.invokeSubscriber(PendingPost pendingPost)方法。
                    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);
        }
    }

    void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            invokeSubscriber(subscription, event);
        }
    }

    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);
        }
    }
}


public class SubscriberMethod {
    final Method method; // 处理事件的Method对象
    final ThreadMode threadMode; //线程模型
    final Class<?> eventType; //事件类型
    final int priority; //事件优先级
    final boolean sticky; //是否是粘性事件
    String methodString;
}

final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;
}

findSubscriberMethods

class SubscriberMethodFinder {
    private static final int MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
    private static final int POOL_SIZE = 4;
    private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
    
    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // 1、先从之前缓存的集合中获取
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            // 2、如果之前缓存了,直接返回
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) { //ignoreGeneratedIndex一般为false
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            // 3、获取所有订阅方法集合
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            // 4、放入缓存集合中
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }
    
    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        // 5、从数组中获取FindState对象
        // 如果有直接返回,如果没有创建一个新的FindState对象
        FindState findState = prepareFindState();
        // 6、根据事件订阅者初始化findState
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            // 7、获取subscriberInfo,初始化为null
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                // 8、通过反射的方式获取订阅者中的Method,默认情况
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }
    
    private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new FindState();
    }
    
    private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // 9、订阅者中所有声明的方法,放入数组中
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // 10、获取订阅者中声明的public方法,设置跳过父类
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        // 遍历这些方法
        for (Method method : methods) {
            // 11、获取方法的修饰符:public、private等等
            int modifiers = method.getModifiers();
            // 12、订阅方法为public同时不是abstract、static
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                // 13、方法参数类型数组
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    // 14、获取方法的注解
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    // 15、如果有注解
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        // 16、将method和eventType放入到findState进行检查
                        if (findState.checkAdd(method, eventType)) {
                            // 17、获取注解中的threadMode对象
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            // 18、新建一个SubscriberMethod对象,同时加入到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");
            }
        }
    }
    
    // 从findState中获取订阅者所有方法并释放
    private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        // 获取订阅者所有订阅方法集合
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        // findState进行回收
        findState.recycle();
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                if (FIND_STATE_POOL[i] == null) {
                    FIND_STATE_POOL[i] = findState;
                    break;
                }
            }
        }
        // 返回集合
        return subscriberMethods;
    }
}

小结

  1. 根据单例设计模式创建一个EventBus对象,同时创建一个EventBus.Builder对象对EventBus进行初始化,其中有三个比较重要的集合和一个SubscriberMethodFinder对象。
  2. 调用register方法,首先通过反射获取到订阅者的Class对象。
  3. 通过SubscriberMethodFinder对象获取订阅者中所有订阅的事件集合,它先从缓存中获取,如果缓存中有,直接返回;如果缓存中没有,通过反射的方式去遍历订阅者内部被注解的方法,将这些方法放入到集合中进行返回。
  4. 遍历第三步获取的集合,将订阅者和事件进行绑定。
  5. 在绑定之后会判断绑定的事件是否是粘性事件,如果是粘性事件,直接调用postToSubscription方法,将之前发送的粘性事件发送给订阅者。

post

public class EventBus {
    ...
        public void post(Object event) {
        // 1、获取当前线程的PostingThreadState,这是一个ThreadLocal对象
        PostingThreadState postingState = currentPostingThreadState.get();
        // 2、当前线程的事件集合
        List<Object> eventQueue = postingState.eventQueue;
        // 3、将要发送的事件加入到集合中
        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 {
                // 4、只要事件集合中还有事件,就一直发送
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

    // currentPostingThreadState是包含了PostingThreadState的ThreadLocal对象
    // ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据, 并且线程之间的数据是相互独立的。
    // 其内部通过创建一个它包裹的泛型对象的数组,不同的线程对应不同的数组索引,每个线程通过get方法获取对应的线程数据。
    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

    // 每个线程中存储的数据
    final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<>(); // 线程的事件队列
        boolean isPosting; //是否正在发送中
        boolean isMainThread; //是否在主线程中发送
        Subscription subscription; //事件订阅者和订阅事件的封装
        Object event; //事件对象
        boolean canceled; //是否被取消发送
    }

    ...

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        // 5、获取事件的Class对象
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) { // eventInheritance一般为true
            // 6、 找到当前的event的所有 父类和实现的接口 的class集合
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                // 7、遍历集合发送单个事件
                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));
            }
        }
    }

    private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
        synchronized (eventTypesCache) {
            // 获取事件集合
            List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
            if (eventTypes == null) { //如果为空
                eventTypes = new ArrayList<>();
                Class<?> clazz = eventClass;
                while (clazz != null) {
                    eventTypes.add(clazz); //添加事件
                    addInterfaces(eventTypes, clazz.getInterfaces()); //添加当前事件的接口class
                    clazz = clazz.getSuperclass();// 获取当前事件的父类
                }
                eventTypesCache.put(eventClass, eventTypes);
            }
            return eventTypes;
        }
    }

    //循环添加当前事件的接口class
    static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
        for (Class<?> interfaceClass : interfaces) {
            if (!eventTypes.contains(interfaceClass)) {
                eventTypes.add(interfaceClass);
                addInterfaces(eventTypes, interfaceClass.getInterfaces());
            }
        }
    }

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 8、根据事件获取所有订阅它的订阅者
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            // 9、遍历集合
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    // 10、将事件发送给订阅者
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    // 11、重置postingState
                    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) {
        // 12、根据订阅方法的线程模式调用订阅方法
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING: //默认类型,表示发送事件操作直接调用订阅者的响应方法,不需要进行线程间的切换
                invokeSubscriber(subscription, event);
                break;
            case MAIN: //主线程,表示订阅者的响应方法在主线程进行接收事件
                if (isMainThread) { //如果发送者在主线程
                    invokeSubscriber(subscription, event);//直接调用订阅者的响应方法
                } else { //如果事件的发送者不是主线程
                    //添加到mainThreadPoster的队列中去,在主线程中调用响应方法
                    mainThreadPoster.enqueue(subscription, event); 
                }
                break;
            case MAIN_ORDERED:// 主线程优先模式
                if (mainThreadPoster != null) {

                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    //如果不是主线程就在消息发送者的线程中进行调用响应方法
                    invokeSubscriber(subscription, event);
                }
                break;
            case BACKGROUND:
                if (isMainThread) {
                    // 如果事件发送者在主线程,加入到backgroundPoster的队列中,在线程池中调用响应方法
                    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);
        }
    }
    ...
}
  1. 获取当前线程的事件集合,将要发送的事件加入到集合中。
  2. 通过循环,只要事件集合中还有事件,就一直发送。
  3. 获取事件的Class对象,找到当前的event的所有父类和实现的接口的class集合。遍历这个集合,调用发送单个事件的方法进行发送。
  4. 根据事件获取所有订阅它的订阅者集合,遍历集合,将事件发送给订阅者。
  5. 发送给订阅者时,根据订阅方法的线程模式调用订阅方法,如果需要线程切换,则切换线程进行调用;否则,直接调用。

postSticky

EventBus.getDefault().postSticky(Object event)

public class EventBus {
    public void postSticky(Object event) {
        synchronized (stickyEvents) {
            // 1、将事件添加到粘性事件集合中
            stickyEvents.put(event.getClass(), event);
        }
        // 2、发送事件
        post(event);
    }
}
  1. 将粘性事件加入到EventBus对象的粘性事件集合中,当有新的订阅者进入后,如果该订阅者订阅了该粘性事件,可以直接发送给订阅者。
  2. 将粘性事件发送给已有的事件订阅者。

unregister

EventBus.getDefault().unregister(Object subscriber)

解注册的方法。

public class EventBus {
    ...
        public synchronized void unregister(Object subscriber) {
        // 1、获取订阅者订阅的所有事件
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            // 2、遍历集合
            for (Class<?> eventType : subscribedTypes) {
                // 3、将该订阅者的从订阅该事件的所有订阅者集合中移除
                unsubscribeByEventType(subscriber, eventType);
            }
            // 4、将订阅者从集合中移除
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        // 获取该事件的所有订阅者
        List<Subscription> 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--;
                }
            }
        }
    }
    ...
}

1、获取订阅者的所有订阅方法,遍历这些方法。然后拿到每个方法对应的所有订阅者集合,将订阅者从集合中移除。
2、移除订阅者中所有的订阅方法。


参考:

  1. greenrobot/EventBus(github.com)
  2. EventBus源码解析 - 掘金 (juejin.cn)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2251799.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深度学习笔记——生成对抗网络GAN

本文详细介绍早期生成式AI的代表性模型&#xff1a;生成对抗网络GAN。 文章目录 一、基本结构生成器判别器 二、损失函数判别器生成器交替优化目标函数 三、GAN 的训练过程训练流程概述训练流程步骤1. 初始化参数和超参数2. 定义损失函数3. 训练过程的迭代判别器训练步骤生成器…

成都睿明智科技有限公司抖音电商服务的新引擎

在这个短视频风起云涌的时代&#xff0c;抖音不仅成为了人们休闲娱乐的首选&#xff0c;更是商家们竞相角逐的电商新蓝海。在这片充满机遇与挑战的海域中&#xff0c;成都睿明智科技有限公司如同一艘装备精良的航船&#xff0c;引领着众多企业向抖音电商的深水区进发。今天&…

51c视觉~YOLO~合集4

我自己的原文哦~ https://blog.51cto.com/whaosoft/12512597 1、Yolo8 1.1、检测PCB元件 技术世界正在以惊人的速度发展&#xff0c;而这种转变的核心是一个革命性的工具 — 计算机视觉。它最有趣的应用之一是电子印刷电路板 &#xff08;PCB&#xff09; 的检测和分析。本文…

Jenkins的使用

文章目录 一、Jenkins是什么\有什么用\与GitLab的对比二、Jenkins的安装与配置Jenkins的安装方式在Linux上安装Jenkins&#xff1a;在Windows上安装Jenkins&#xff1a;配置Jenkins&#xff1a; &#xff08;可选&#xff09;配置启动用户为root&#xff08;一定要是root吗??…

图论入门教程:GTM173 Graph Theory

这是本图论的入门教材&#xff0c;Graph Theory Fifth Edition&#xff0c;隶属于著名的GTM系列&#xff0c;作者是Reinhard Diestel。这是本对新人友好的教材&#xff0c;之前本科上离散数学的课时&#xff0c;因为涉及到图论&#xff0c;而学校的课堂又太水让我心生不满&…

QT5 Creator (Mingw编译器) 调用VS2019 (阿里云 oss C++库) 报错的解决方法

方法就是不要用VS2019编译&#xff0c;要用MINgw32编译。 编译命令如下&#xff1a; cmake -G "MinGW Makefiles" ^-DCMAKE_MAKE_PROGRAMD:\qt\Tools\mingw810_32\bin\mingw32-make.exe ^-DCMAKE_C_COMPILERD:\qt\Tools\mingw810_32\bin\gcc.exe ^-DCMAKE_CXX_COMP…

反向传播、梯度下降与学习率:深度学习中的优化艺术

目录 反向传播&#xff1a;神经网络的学习机制 梯度下降&#xff1a;优化算法的基石 学习率&#xff1a;平衡速度与稳定性的关键 学习率的调整策略 固定学习率 学习率衰减 自适应学习率 梯度消失与梯度爆炸 结语 在深度学习的领域中&#xff0c;构建一个有效的神经网络…

论文笔记(五十九)A survey of robot manipulation in contact

A survey of robot manipulation in contact 文章概括摘要1. 引言解释柔顺性控制的概念&#xff1a;应用实例&#xff1a; 2. 需要接触操控的任务2.1 环境塑造2.2 工件对齐2.3 关节运动2.4 双臂接触操控 3. 接触操控中的控制3.1 力控制3.2 阻抗控制3.3 顺应控制 4. 接触操控中的…

881.救生艇

目录 题目过程 题目 给定数组 people 。people[i]表示第 i 个人的体重 &#xff0c;船的数量不限&#xff0c;每艘船可以承载的最大重量为 limit。 每艘船最多可同时载两人&#xff0c;但条件是这些人的重量之和最多为 limit。 返回 承载所有人所需的最小船数 。 过程 cla…

【汇编】逻辑指令

文章目录 一、逻辑运算指令&#xff08;一&#xff09;各逻辑运算指令格式及操作&#xff08;1&#xff09;逻辑非指令 NOT&#xff08;2&#xff09;逻辑与指令 AND&#xff08;3&#xff09;逻辑或指令 OR&#xff08;4&#xff09;异或指令 XOR&#xff08;5&#xff09;测试…

网页开发的http基础知识

请求方式-GET&#xff1a;请求参数在请求行中&#xff0c;没有请求体&#xff0c;如&#xff1a;/brand/findAll?nameoPPo&status1。GET请求大小在浏览器中是有限制的请求方式-POST&#xff1a;请求参数在请求体中&#xff0c;POST请求大小是没有限制的 HTTP请求&#xf…

如何做好一份技术文档

如何做好一份技术文档 以下是本人的一些微不足道的经验&#xff0c;希望可以与大家互相交流学习 方向一&#xff1a;技术文档的规划布局 确定整体架构 创建一份优秀技术文档的第一步是规划其整体架构。一个好的架构应能引导读者理解文档的内容&#xff0c;同时提供一个逻辑清…

Springboot——SseEmitter流式输出

文章目录 前言SseEmitter 简介测试demo注意点异常一 ResponseBodyEmitter is already set complete 前言 最近做AI类的开发&#xff0c;看到各大AI模型的输出方式都是采取的一种EventStream的方式实现。 不是通常的等接口处理完成后&#xff0c;一次性返回。 而是片段式的处理…

Java 虚拟机:承载 Java 生态的神奇魔盒

在软件开发的世界里&#xff0c;Java 虚拟机&#xff08;JVM&#xff09;就像一位智慧的管家&#xff0c;默默守护着 Java 生态系统的运行。它不仅让 Java 实现了"一次编写&#xff0c;到处运行"的梦想&#xff0c;更是成为了多种编程语言的运行平台。让我们一起走进…

sqlmap详细使用

SQLmap使用详解 SQLmap&#xff08;常规&#xff09;使用步骤 1、查询注入点 python sqlmap.py -u http://127.0.0.1/sqli-labs/Less-1/?id12、查询所有数据库 python sqlmap.py -u http://127.0.0.1/sqli-labs/Less-1/?id1 --dbs3、查询当前数据库 python sqlmap.py -u htt…

【Linux】Linux2.6内核进程调度队列与调度原理

目录 一、进程管理中的部分概念二、寄存器三、进程切换四、Linux2.6内核进程调度队列与调度原理结尾 一、进程管理中的部分概念 竞争性: 系统进程数目众多&#xff0c;而CPU资源只有少量&#xff0c;甚至1个&#xff0c;所以进程之间是具有竞争属性的。为了高效完成任务&#…

Qt 详解QRubberBand

文章目录 QRubberBand 简介前言 QRubberBand 的作用QRubberBand 的主要功能QRubberBand 的常用方法QRubberBand 的典型应用场景示例代码总结 QRubberBand 简介 前言 在 Qt 中&#xff0c;QRubberBand 是一个非常实用的控件&#xff0c;它通常用于图形界面中的“选择区域”功能…

python股票数据分析(Pandas)练习

需求&#xff1a; 使用pandas读取一个CSV文件&#xff0c;文件内容包括股票名称、价格和交易量。完成以下任务&#xff1a; 找出价格最高的股票&#xff1b; 计算总交易量&#xff1b; 绘制价格折线图。 代码实现&#xff1a; import pandas as pd import matplotlib.pyplot …

Jenkins Nginx Vue项目自动化部署

目录 一、环境准备 1.1 Jenkins搭建 1.2 NVM和Nodejs安装 1.3 Nginx安装 二、Jenkins配置 2.1 相关插件安装 2.2 全局工具安装 2.3 环境变量配置 2.4 邮箱配置&#xff08;构建后发送邮件&#xff09; 2.5 任务配置 三、Nginx配置 3.1 配置路由转发 四、部署项目 …

JUnit介绍:单元测试

1、什么是单元测试 单元测试是针对最小的功能单元编写测试代码&#xff08;Java 程序最小的功能单元是方法&#xff09;单元测试就是针对单个Java方法的测试。 2、为什么要使用单元测试 确保单个方法运行正常&#xff1b; 如果修改了代码&#xff0c;只需要确保其对应的单元…