1
votes

I am experimenting a bit with flows in kotlin and asked myself a question: Will my flows be cancelled if one of the operations within the flow throws an exception even If I use .catch?

If not, how can I cancel my flow when an exception occurs even while using .catch?

Example

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

Another Example

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

1 Answers

2
votes

If the execution of the Flow throws an Exception, it will cancel and complete the Flow during collection. The collect() function call will throw the Exception if the Flow.catch operator was not used.

If you emit an Exception like in your example, it's just another object in the Flow. Since you have not specified the Flow's type, it's implicitly choosing a type that's common between String and Exception. I think you have a Flow<Serializable> since that's a common supertype of both. If you had specified Flow<String>, it would not allow you to emit an Exception.