Android:坑-协程-订阅时序导致收不到流

坑-协程-订阅时序导致收不到流

封装了一个MVI框架,极低概率出现这样一种问题:

页面A、页面B,A跳转B,B再返回A,然后A立刻再跳入B,偶现ViewModelScope.launch{} 域中的ShareFlow没有触发。

代码:

kt 复制代码
abstract class BaseFlowViewModel<VS : ViewState, I : UserIntent,Changes: ReduceViewStateChange<VS>>(
    application: Application,
    firstViewState: VS
) : BaseViewModel(application) {

    private val _viewState: MutableStateFlow<VS> = MutableStateFlow(firstViewState)
    val viewState : MutableStateFlow<VS> = _viewState

    private val _intent:MutableSharedFlow<I> = MutableSharedFlow(extraBufferCapacity = 5, onBufferOverflow=BufferOverflow.DROP_OLDEST)

    protected abstract suspend fun realSendIntent(intent: I)

    protected abstract suspend fun catchError(throwable: Throwable)

    fun sendIntent(intent: I){
        Log.d("wuxu","sendIntent!!!")
        viewModelScope.launch {
            _intent.emit(intent)
        }
    }

    init {
        viewModelScope.launch(Dispatchers.IO+SupervisorJob()) {
            Log.d("wuxu","init!!!")
            _intent
                .onEach {
                    Log.d("wuxu","viewModelScope onEach $it")
                    realSendIntent(it)
                }
                .catch {
                    catchError(it)
                }
                .collect()
        }
    }
}

猜想原因只能有三个:

  1. scope被cancel;- 通过源码及日志输出判断,每次页面进入都会创建新的ViewModelScope,不存在cancel的情况;
  2. 协程域异常;- 这个我使用的是SupervisorJob(),所以排除
  3. collect()订阅,比emit晚。 - 最终确定是这个

最终日志输出:

正常:init->sendIntent 出问题时:sendIntent->init ,此时没有collect,导致无法触发流。

相关推荐
sweetying1 小时前
30了,人生按部就班
android·程序员
用户2018792831672 小时前
Binder驱动缓冲区的工作机制答疑
android
真夜2 小时前
关于rngh手势与Slider组件手势与事件冲突解决问题记录
android·javascript·app
用户2018792831672 小时前
浅析Binder通信的三种调用方式
android
用户092 小时前
深入了解 Android 16KB内存页面
android·kotlin
火车叼位3 小时前
Android Studio与命令行Gradle表现不一致问题分析
android
前行的小黑炭5 小时前
【Android】 Context使用不当,存在内存泄漏,语言不生效等等
android·kotlin·app
前行的小黑炭6 小时前
【Android】CoordinatorLayout详解;实现一个交互动画的效果(上滑隐藏,下滑出现);附例子
android·kotlin·app
用户20187928316718 小时前
Android黑夜白天模式切换原理分析
android
芦半山18 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android