Sobes.tech
Junior — Middle

How is error handling performed in data streams (Flow)?

sobes.tech AI

Answer from AI

In Kotlin Flow, error handling is performed using the catch operator, which intercepts exceptions that occur in the data stream. This allows you to handle the error, for example, by logging it, replacing the erroneous element, or terminating the stream with a specific action.

Example:

flowOf(1, 2, 0, 4)
    .map { 10 / it } // an exception will occur when dividing by 0
    .catch { e -> emit(-1) } // emit -1 in case of error
    .collect { value -> println(value) }

You can also use the onCompletion operator to perform actions after the stream finishes, including error handling.