Raj*_*esh 3 asynchronous reactive-programming kotlin rx-java kotlin-flow
如果代码中发生某些情况,我想取消 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
}
}
Run Code Online (Sandbox Code Playgroud)
并称其为
test().collect { println(it)}
Run Code Online (Sandbox Code Playgroud)
问题是,如何停止流在某些条件下(来自流生成器或流生成器之外)产生任何内容?
fun test(): Flow<String> = flow {
val lst = listOf("A", "B", "C")
while(true) {
lst.forEach { emit(it) }
if (someCondition) {
return@flow
}
}
}
Run Code Online (Sandbox Code Playgroud)
return@flow立即从flowlambda 返回,因此流程将结束。作为另一种选择,您可以在条件发生时只循环break。while(true)
| 归档时间: |
|
| 查看次数: |
4955 次 |
| 最近记录: |