如果发生异常,流程是否取消

And*_*rew 2 kotlin kotlin-coroutines kotlin-flow

我正在 kotlin 中尝试一些流程,并问自己一个问题:如果流程中的其中一个操作抛出异常,即使我使用 .catch,我的流程也会被取消吗?

如果没有,即使在使用 .catch 时发生异常,如何取消流程?

例子

fun testFlow() = flow {
   emit("Test")
   emit(Exception("Error"))
   emit("Test2") // This should not be emitted
}.catch { e -> println("Showing UI $e") }
Run Code Online (Sandbox Code Playgroud)

另一个例子

fun testFlow2() = flow {
   emit("Test")
   throw Exception("Error")
   emit("Test2") // This should not be emitted
}.catch { e -> println("Showing UI $e") }
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 5

如果Flow的执行抛出异常,它将在收集期间取消并完成Flow。如果未使用运算符,函数collect()调用将抛出异常。Flow.catch

如果您像示例中那样发出异常,那么它只是流程中的另一个对象。由于您尚未指定 Flow 的类型,因此它会隐式选择 String 和 Exception 之间通用的类型。我认为你有一个,Flow<Serializable>因为这是两者的共同超类型。如果您指定了Flow<String>,它将不允许您发出异常。