More on Flow Lifecycle Functions
See some more flow lifecycle functions in action.
We'll cover the following...
We'll cover the following...
catch
At any point of flow building or processing, an exception might occur. Such an exception will flow down, closing each processing step on the way; however, it can be caught and managed. To do so, we can use the catch method. This listener receives the exception as an argument and allows us to perform recovering operations.
package kotlinx.coroutines.app
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onEach
class MyError : Throwable("My error")
val flow = flow {
emit(1)
emit(2)
throw MyError()
}
suspend fun main(): Unit {
flow.onEach { println("Got $it") }
.catch { println("Caught $it") }
.collect { println("Collected $it") }
}Using catch
Note: In the example above, notice that
onEachdoes not react to an exception. The same happens with other functions likemap,filter, etc. Only theonCompletionhandler will be called.
The catch method stops an exception by catching it. The previous steps have already been completed, but catch ...