LiveData 粘性事件解决方案 附:简易LiveDataBus

本文介绍了针对LiveData的粘性事件解决方案,探讨了如何在Android应用中实现粘性事件传递,并附带了一个简单的LiveDataBus实现,用于增强LiveData的功能。

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

LiveData 粘性事件解决方案

**LiveData源码分析**
private void considerNotify(LiveData.ObserverWrapper observer) {
   
   
        if (!observer.mActive) {
   
   
            return;
        }
        // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
        //
        // we still first check observer.active to keep it as the entrance for events. So even if
        // the observer moved to an active state, if we've not received that event, we better not
        // notify for a more predictable notification order.
        if (!observer.shouldBeActive()) {
   
   
            observer.activeStateChanged(false);
            return;
        }

        //上面的判断是生命周期的拦截
        //一般事件流程 :new Observe(mVersion=-1)-> 注册观察者(mLastVersion=-1)-> setValue(mVersion++) 
        //粘性事件的流程 :new Observe(mVersion=-1)-> setValue(mVersion++) ->注册观察者(mLastVersion=-1)
        //此时 mLastVersion=-1 , mVersion=0 ,未触发拦截导致首次注册时会触发接口回调造成粘性事件
        if (observer.mLastVersion >= mVersion) {
   
   
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值