如果代码中发生某些情况,我想取消 kotlin 流程。
假设我有一个方法如下
fun test(): Flow<String> = flow {
val lst = listOf("A", "B", "C")
while(true) {
lst.forEach { emit(it) }
//If some condition occurs, need to return from here, else continue
//How to stop flow here
}
}
并称之为
test().collect { println(it)}
问题是,如何在某些条件下(从流构建器或在流构建器之外)停止流以产生任何东西?
最佳答案
fun test(): Flow<String> = flow {
val lst = listOf("A", "B", "C")
while(true) {
lst.forEach { emit(it) }
if (someCondition) {
return@flow
}
}
}
return@flow
立即返回 flow
lambda,因此流程将结束。作为另一种选择,您可以仅 break
您的 while(true)
当您的条件发生时循环。
关于asynchronous - 发生某些情况时如何停止 Kotlin 流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59956312/