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,导致无法触发流。

相关推荐
机智的张尼玛13 小时前
我基于 Kotlin Multiplatform 实现了一套跨平台的弱网离线同步引擎
android·开源·kotlin
安卓修改大师16 小时前
安卓修改大师反编译引擎Apktool深度解析:版本选择、参数说明与实战技巧
android
error:(16 小时前
【系统与实战双精通】VS Code 调试 ROS2 Python 节点与 Launch 系统指南
android·java·python
黄林晴18 小时前
Kuikly 是什么?和KMP有什么关系?
android·前端
帅次19 小时前
Android 高级工程师面试:Kotlin 语法基础 近1年高频追问 22 题
android·面试·kotlin·扩展函数·空安全
想你依然心痛19 小时前
嵌入式日志系统:分级日志、环形缓冲区与远程输出——运行时调试、非侵入
android·前端·javascript
用户693717500138420 小时前
AI Agent 里的 Loop 到底是什么?
android·前端·后端
海天鹰21 小时前
安卓分割空字符串数组长度为1
android
Coffeeee21 小时前
从 Android 15 到 Android 17,谷歌猝不及防的音频改动
android·前端·google
用户693717500138421 小时前
AI 领域的 Harness,到底是什么意思?
android·前端·后端