You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SharingStarted.Lazily时onSubscription内上游发射值未被收集问题咨询

关于SharedFlow<T>.onSubscription在SharingStarted.Lazily下的行为疑问

返回一个流,该流会在当前共享流开始被收集(即订阅注册完成后)调用指定动作。该动作会在上游流向此订阅发射任何值之前、订阅建立之后执行。可以保证,在onSubscription动作内部或紧随其后向上游流的所有发射都会被此订阅收集。动作的接收者是FlowCollector,因此onSubscription可以发射额外元素。

但当共享流以started = SharingStarted.Lazily创建时,在onSubscription内部向上游流发射的值不会被该订阅收集,具体示例如下:

SharingStarted.Lazily 示例

suspend fun main() {
    coroutineScope {
        val upstream = MutableSharedFlow<Int>()
        upstream.shareIn(
            scope = this,
            started = SharingStarted.Lazily,
        ).onSubscription {
            println("subscription")
            upstream.emit(42)
        }.collect {
            println("value $it")
        }
    }
}

输出:

subscription

SharingStarted.Eagerly 示例

suspend fun main() {
    coroutineScope {
        val upstream = MutableSharedFlow<Int>()
        upstream.shareIn(
            scope = this,
            started = SharingStarted.Eagerly,
        ).onSubscription {
            println("subscription")
            upstream.emit(42)
        }.collect {
            println("value $it")
        }
    }
}

输出:

subscription
value 42

我清楚可以直接使用emit(42)替代upstream.emit(42),但需求是必须向上游流发射值。我尝试理解为何使用SharingStarted.Lazily时onSubscription的表现不符合文档描述,但始终没能完全理清,希望有人能详细解释此现象的原因,最好结合Flow实现代码中的具体逻辑说明为何此时无法保证发射值被收集。

内容的提问来源于stack exchange,提问作者Simon Forsberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:05:08