Hey all. I am trying to race calls to 2 APIs where...
# arrow
l
Hey all. I am trying to race calls to 2 APIs where I keep retrying it till I either get the proper data or till it times out. In case, I hit the timeout, I would like to return the list of
Throwable
that were returned while handling the API. I came up with this code not sure if this is the optimal way to do so:
Copy code
suspend fun scheduleCall(service: Service, handleError: (Throwable) -> Unit) =
    (Schedule.doWhile<Either<Throwable, Data>> { it.isEmpty() }
            .logOutput { it.mapLeft { throwable -> handleError(throwable) } })
        .repeat { service.call() }
suspend fun callServices(
    a: Service,
    b: Service
): Either<List<Throwable>, String> {
  val errors = mutableListOf<Throwable>()
  val winner =
      raceN(
          <http://Dispatchers.IO|Dispatchers.IO>,
          { scheduleCall(a) { errors += it } },
          { scheduleCall(b) { errors += it } },
          { delay(60.seconds) })
  return when (winner) {
    is First -> "A".right()
    is Second -> "B".right()
    is Third -> errors.left()
  }
}
s
You want all errors of both
scheduleCall
with
(a)
and
(b)
not just of the winner of the race?
l
well I wanted to return the errors in case both the API calls ran into exceptions
s
Okay, I'm a bit confused. Let me phrase what I understood from the "requirements". There are two functions. Let's call them
fa
, and
fb
. They both return
Either<Throwable, Data>
. You need to run them in parallel until they succeed, with a timeout of 60s? If they don't succeed you want to know all errors that occurred for both
fa
and
fb
? Or are do you need to race them in parallel until they succeed,....
l
You need to run them in parallel until they succeed, with a timeout of 60s? If they don't succeed you want to know all errors that occurred for both
fa
and
fb
?
Yes, I am looking to implement something like that. Sorry about the confusion