Table of contents
In this series of articles , we are discussing about Kotlin flows and in this article we will discuss about Flows Exception handling
try/catch operator
- We can simply enclose the collect block with try/catch as follows
suspend fun main(): Unit = coroutineScope {
launch {
val brandFlow = brandFlow()
try {
brandFlow.collect { name ->
println(name)
}
} catch (ex: Exception) {
println("Caught Exception $ex")
}
}
}
private fun brandFlow() = flow {
emit("Google Pixel")
emit("Samsung")
emit("Apple")
throw Exception("Anonymous Exception")
}
What happens if an exception is thrown in collect block , one option is to use try/catch block which might make the code more complex .
Call to emit() internally leads to the execution of collect block (Flows under the hood)
OnEach()
Returns a flow that invokes the given action before each value of the upstream flow is emitted downstream.
Adding this operator before catch{...} block ensures that all the exception are caught and the collect{...} will be empty as we see in the below code
Exception Transparency
1.A Downstream exception must always be propagated to collector
2.Once an uncaught exception is thrown downstream , the flow isn't allowed to emit additional values
use catch operator instead of try/catch block
catch()
only catches upstream exception and passes all downstream exceptions
use this operator to follow the exception transparency principle .
When flow builder throws exception , the applied operators will be stopped
suspend fun main(): Unit = coroutineScope {
launch {
val brandFlow = brandFlow()
brandFlow
.onEach { name ->
println(name)
}
.catch { cause ->
println("Caught Exception : $cause")
}
.collect{}
}
}
private fun brandFlow() = flow {
emit("Google Pixel")
emit("Samsung")
throw Exception("Anonymous Exception")
emit("Apple")
}
Please run and play with above Kotlin codes to understand it in a better way .Just copy and paste it in a kotlin file .
In the next article , we will discuss about Flow intermediate operators .
Please leave your comments to improve and discuss more
Happy and Enjoy coding