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

相关推荐
快乐觉主吖15 分钟前
Unity安卓平台开发,启动app并传参
android·unity·游戏引擎
原来如此。24 分钟前
Android 轻松实现 增强版灵活的 滑动式表格视图
android
jiet_h6 小时前
Android Kotlin 算法详解:链表相关
android·算法·kotlin
@老蝴7 小时前
C语言 — 动态内存管理
android·c语言·开发语言
每次的天空9 小时前
Android第十一次面试flutter篇
android·flutter·面试
renxhui11 小时前
Android 性能优化(四):卡顿优化
android·性能优化
二流小码农11 小时前
鸿蒙开发:UI界面分析利器ArkUI Inspector
android·ios·harmonyos
CYRUS_STUDIO11 小时前
FART 精准脱壳:通过配置文件控制脱壳节奏与范围
android·安全·逆向
小疯仔11 小时前
使用el-input数字校验,输入汉字之后校验取消不掉
android·开发语言·javascript
墨狂之逸才12 小时前
Data Binding Conversion 详解
android