EventBus - 3 源码解析-1:EventBus对象构建/如何进行线程调度(整理中)

本文详细解析了EventBus的默认实例获取、线程调度策略,包括ThreadMode.MAIN、BACKGROUND和ASYNC的工作原理,以及订阅者管理和事件分发机制。通过构造器创建EventBus单例,并探讨了如何根据不同的ThreadMode进行事件推送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


 EventBus.getDefault().register(this);

/** Convenience singleton for apps using a process-wide EventBus instance. */
  public static EventBus getDefault() {
        EventBus instance = defaultInstance;
        if (instance == null) {
            synchronized (EventBus.class) {
                instance = EventBus.defaultInstance;
                if (instance == null) {
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
   }

一个很经典的单例模式,调用EventBus的构造器创建EventBus对象;

/**
     * 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);
    }
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; //一般情况为0
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        //一般情况参数为null、false、false;该对象我们后面会介绍
        logSubscriberExceptions = builder.logSubscriberExceptions; //一般情况为true
        logNoSubscriberMessages = builder.logNoSubscriberMessages; //一般情况为true
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent; //一般情况为true
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;//一般情况为true
        throwSubscriberException = builder.throwSubscriberException; //一般情况为false
        eventInheritance = builder.eventInheritance; //一般情况为true
        executorService = builder.executorService; //一个newCachedThreadPool()
}
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();    
List<SubscriberInfoIndex> subscriberInfoIndexes;  
boolean strictMethodVerification;  
boolean ignoreGeneratedIndex;  
boolean logSubscriberExceptions = true;  
boolean logNoSubscriberMessages = true;  
boolean sendSubscriberExceptionEvent = true;  
boolean sendNoSubscriberEvent = true;  
boolean throwSubscriberException;  
boolean eventInheritance = true;  
ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;  
//总结:eventInheritance、logXX和sendXX全为true;其它全为false;
到此为止我们分析了调用getDefault方法得到的EventBus对象;
该对象存储有如下两个集合
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; 
  • 以事件类型为键,每个事件对应一个Subscription对象的集合。EventBus一旦收到一个事件就会遍历它对应的Subscription集合,将该事件推送给Subscription处理。对于Subscription对象的如何构建和使用后文将会给出。
Map<Object, List<Class<?>>> typesBySubscriber; 
  • 以事件订阅者为键(事件订阅者就是register方法的参数),每个订阅者对应一组它能接收的事件类型集合。一旦订阅者和EventBus解除注册,即调用unregister方法时,EventBus就会取出订阅者对应的所有事件类型,去subscriptionsByEventType中移除该事件对应的Subscription对象集合中的和订阅者关联的Subscription

该对象存储有如下四个执行器
ExecutorService executorService = Executors.newCachedThreadPool();  
  • 是一个线程池,ThreadPoolExecutor(0.Integer.MAX_VALUE,....)
HandlerPoster mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
  • 对应ThreadMode.MAIN模式,是一个继承Handler的类;事件的推送在其HandlerMessage方法中执行
private final BackgroundPoster backgroundPoster;
  • 对应ThreadMode.BACKGROUND模式,是一个实现了Runnable方法的类;事件的推送就是将自己扔给executorService,如果当前对象已经在执行了,则只是将事件放入到BackgroundPoster中的一个队列中;否则将自己交给线程池执行其run方法。BackgroundPoster对象的run方法会一直遍历这个队列,直到队列没有数据则退出run方法。
private final AsyncPoster asyncPoster;   
  • 对应ThreadMode.ASYNC模式,是一个实现了Runnable方法的类;相对于BackgroundPoster这里一旦有事件需要分发则立即将自己扔给线程池,而不是直接将事件扔给队列就完了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值