Howdy, could someone suggest a better way to wrap ...
# arrow
a
Howdy, could someone suggest a better way to wrap a
callbackFlow
in
Either
? I came up with that but it looks kind of funky:
Copy code
val flow = callbackFlow<Unit> {
    delay(2000)
    cancel(CancellationException("Boom"))
}

Either.catch {
    flow
        .catch { throw RuntimeException(it.message) }
        .collect()
}.mapLeft { it.message?.let { msg -> FlowError.Canceled(msg) } }
s
Hey Alex, What exactly is your use-case? Normally
Flow
would result in many results, but
Either
only has a single result. Are you just interested in capturing the cancelled event, or success? I think here your final result is
Either<FlowError.Canceled?, Unit>
.
s
Reminds me a little of a question I asked on StackOverflow once
a
Hey Simon, in my exact use case I have just a single value that I’m expecting from the flow (along with the possible cancellations/failures). The code snippet that I used was illustrative
s
If you're only expecting a single value, why not use
suspend fun
with
suspendCoroutineCancellable
? Then you could do something like:
Copy code
either<Error, Res> {
  val res: Res = guaranteeCase({ action() }) { exitCase ->
    when(exitCase) {
     ExitCase.Completed -> Unit
     ExitCase.Failure -> Unit
     ExitCase.Cancelled -> shift(FlowError.Canceled(it.message ?: ""))
    }
  }
}
Or
Copy code
either<Error, Res> {
  val res: Res = onCancel({ action() }) {
    shift(..)
  }
}
a
Thank you very much!