what is the idomatic way to cancel a `flow` from w...
# coroutines
b
what is the idomatic way to cancel a
flow
from within with an error? just throw an exception, or is there a function?
k
I do this in exactly one place in our codebase, but beware that it’s got edge cases.
Copy code
flow {
  coroutineScope {
    try {
      ...
    } catch (e: SomeException) {
      // ... perform some side effect...
      cancel(message = "An error happened", cause = e)
    }
  }
}
👎 1
b
if you use
cancel
will it consider a "normal" cancellation? so when you use
.catch()
on the flow later, it won't trigger will it?
oh, and you're cancelling the scope, which will end the flow normally, i want to cancel it with an error
e
Copy code
flow {
    throw exception // will end flow
}.catch {
    // will catch exception
}
using
coroutineScope
inside
flow
makes it way too easy to do things that aren't supported and will throw errors at runtime (such as trying to emit from another coroutine), I wouldn't do that. if you want to end the flow gracefully, you can
return@flow
k
In my case, I wanted to cancel the collector of the flow. Ending it gracefully means that certain operators, like
Flow.first
, would throw exceptions.