【发布时间】:2021-12-24 09:18:03
【问题描述】:
我有一个具有不同状态的父类,这个父类有一个子类列表,每个子类都有不同的状态。我想收集它们中的每一个并取消达到Terminated 状态的那个。类似的东西:
coroutineScope.launch(Dispatcher.IO) {
parent.parentState.collect {
if(it is ParentState.Normal){
it.children.forEach{ child ->
coroutineScope.launch(Dispatcher.IO){
child.childState.collect{
if(it is ChildState.Terminated){
//when this line executed all the collectors stop until I change the states for each one of them..
this.coroutineContext.job.cancel()
} else{
// Do something else for any other state...
}
}
}
}
}
}
}
但是当我这样做时,我正在收集的所有孩子都会停止收集,但如果我更改了每个孩子的状态,它会再次开始收集,而在取消其中一个之前情况并非如此。
所以我的问题是为什么在取消其中一位收藏家的工作时会出现这样的行为?
还有没有更好的“反应式”来写这个?
【问题讨论】:
-
你的代码 sn-p 中的
all the collectors stop是什么意思?该流只有一个收集器。您想取消对达到终止状态的孩子的收集,而其他孩子的流程应该继续,这是您想要的吗? -
没错。其他孩子应该继续。
标签: android kotlin kotlin-coroutines kotlin-flow