如果代码中发生某些情况,我想取消 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
your while(true)
当你的情况发生时循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)