Catching exceptions in Flows
The Flows in your code can encounter CancellationException
when they are canceled or other exceptions when emitting or collecting values. In this section, we will learn how to handle these Kotlin Flow exceptions.
Exceptions can happen in Flows during the collection of values or when using any operators on a Flow. We can handle exceptions in Flows by enclosing the collection of the Flow in our code with a try-catch
block. For example, in the following code, the try-catch
block is used to add exception handling:
class MainActivity : AppCompatActivity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
...
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
try {
...