asynchronous - 发生某些情况时如何停止 Kotlin 流程

标签 asynchronous kotlin rx-java reactive-programming 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
    }
}

并称之为
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/

相关文章:

android - Kotlin:如何在viewModel中观察一次liveData?使用ObserveForever()和removeObserver()

kotlin - 具有不可为空的getter的可为空字段

python - 为什么我应该等待response.read(),但我不需要等待response.status?

c# - 锁定 C# switch case 的首选方式

android - 带加号的Kotlin多行字符串声明

java - 从多个请求中获取带有 id 和响应正文的 map

java - 快速覆盖方法

java - rxJava : composing single with completable and return single

ios - 如何从 URL 按顺序而不是一起将图像加载到 imageView?

javascript - 为什么将我的 JavaScript 库包装在一个匿名函数中可以修复我的竞态条件?