EventBus (二)线程切换

本文深入探讨了EventBus在处理事件时的线程选择,重点关注HandlerPoster组件及其涉及的两个关键对象。同时,文章还讲解了BackgroundPoster的使用,帮助读者理解EventBus如何进行后台线程的切换。

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

线程选择

/**
 *
 * @param subscription
 * @param event
 * @param isMainThread      发送通知时,所在线程
 */
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 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);
    }
}

其中呢,isMainThread是怎么来的呢
//根据looper判断postingState所在线程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postToSubscription(subscription, event, postingState.isMainThread);

//接下来,看看HandlerPoster是什么情况
    //在EventBus创建时,就已经同时创建了
    EventBus(EventBusBuilder builder) {
        //....
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        //....
    }

 

HandlerPoster

    /**
     * HandlerPoster就是一个Handler,只不过我们平时是在Activity里使用,这里抽取出来 * 跟我们平时没什么差别(主线程)
     */
    final class HandlerPoster ext
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值