More on Flow Lifecycle Functions
Explore Kotlin Flow lifecycle functions including catch for exception handling, flowOn for modifying coroutine context upstream, and launchIn for starting flows in new coroutines. This lesson helps you manage flow events and errors effectively, enhancing your Android coroutine skills.
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") }
}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 ...