我可以按以下方式启动我的stateFlow集合
val collectingScope = CoroutineScope(Dispatchers.Default)
val stateFlow = MutableStateFlow(0)
val myJob = collectingScope.launch {
stateFlow.collect {
println("collected $it")
}
}我可以用
myJob.cancel()但是我想知道我是否也可以通过stateFlow取消它呢?我看到有一个cancel()函数,但它被废弃了
@Deprecated(
message = "cancel() is resolved into the extension of outer CoroutineScope which is likely to be an error." +
"Use currentCoroutineContext().cancel() instead or specify the receiver of cancel() explicitly",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("currentCoroutineContext().cancel(cause)")
)
public fun FlowCollector<*>.cancel(cause: CancellationException? = null): Unit = noImpl()如果可以的话,取消也会自动取消myJob吗?
发布于 2022-10-24 03:28:14
不是的。StateFlows不能取消。见文档
状态流永远不会完成。对状态流上的Flow.collect的调用永远不会正常完成,Flow.launchIn函数启动的协同线也不会正常完成。状态流的活动收集器称为订阅服务器。
https://stackoverflow.com/questions/74168785
复制相似问题