当我试图从流中过早取消时,我注意到一个奇怪的行为。看看下面的例子。
这是一个发出整数值的简单流程
private fun createFlow() = flow {
repeat(10000) {
emit(it)
}
}
然后我createFlow
使用这段代码调用函数
CoroutineScope(Dispatchers.Main).launch {
createFlow().collect {
Log.i("Main", "$it isActive $isActive")
if (it == 2) {
cancel()
}
}
}
这是打印出来的
0 isActive true
1 isActive true
2 isActive true
3 isActive false
4 isActive false
etc...etc
现在我希望流一旦达到 2 的值就应该停止发射整数,但实际上它会将 isActive 标志切换为 false 并继续发射而不会停止。
当我在排放之间添加延迟时,流程的行为与我预期的一样。
private fun createFlow() = flow {
repeat(10000) {
delay(500) //add a delay
emit(it)
}
}
这是再次调用流程后打印的内容(这是预期的行为)。
0 isActive true
1 isActive true
2 isActive true
如何在不增加延迟的情况下完全取消指定值的流量发射?