https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

CLOVIS

10/17/2020, 12:21 PM
What is the correct way of catching an exception in
Flow.flatMapMerge
? I have this:
Copy code
val f: Flow<CustomObject> = ...
f.flatMapMerge {
  it.customFlow()
}
This works fine as long as there is no exception, however if there is one, the entire flow is cancelled. I tried to write
Copy code
f.flatMapMerge {
  try {
    it.customFlow()
  } catch(e: Throwable) {
    println("Caught")
    emptyFlow()
}
} but that still cancels the flow, instead of just skipping items for which the conversion fails.
Oh, that's because the exception is only thrown during collection. But if I add a
.catch
after the
.flatMapMerge
, the flow has still been cancelled.
z

Zach Klippenstein (he/him) [MOD]

10/17/2020, 2:44 PM
Use the catch operator on the inner flow (customFlow)
c

CLOVIS

10/17/2020, 5:39 PM
Thanks! Not sure how I missed that 😓