1

我有一个流程可能会引发如下错误:

val myFlow = flow {
    emit("1")
    delay(2000)
    emit("2")
    delay(2000)
    emit("3")
    delay(2000)
    emit("4")
    delay(2000)
    throw Exception() // here it would throw an error
    delay(10000)
    emit("6")  // because the flow completes on error, it doesn't emit this
}

我的问题是,即使我添加了.catch { error -> emit("5") }.. 也会引发错误,它仍然会完成流程,因此不会"6"发出。

myFlow.catch { error ->
    emit("5")
}.onEach {
    println("$it")
}.onCompletion {
    println("Complete")
}.launchIn(scope)

结果是:

1
2
3
4
5
Complete

我需要它是:

1
2
3
4
5
6
Complete

我想吞下错误而不是完成流程。我怎样才能做到这一点?

4

1 回答 1

0

这在您当前的示例中是不可能的,因为您的流程中的最后 2 行无法访问。

您应该处理流程内部的异常,这意味着在流程中捕获异常并在您的示例中发出 5。

像这样

val myFlow = flow {
        emit("1")
        delay(2000)
        emit("2")
        delay(2000)
        emit("3")
        delay(2000)
        emit("4")
        delay(2000)
        try {
            throw Exception() // here it would throw an error
        } catch (e: Exception) {
            emit("5")
        }
        delay(10000)
        emit("6")  // because the flow completes on error, it doesn't emit this
    }
于 2020-11-30T19:21:51.823 回答