Skip to content

Retry if the future itself fails #3

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions core/src/main/scala/retries.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,14 @@ trait CountingRetry {
promise: () => Future[T],
success: Success[T],
orElse: Int => Future[T]
)(implicit executor: ExecutionContext) = {
)(implicit executor: ExecutionContext): Future[T] = {
val fut = promise()
fut.flatMap { res =>
if (max < 1 || success.predicate(res)) fut
else orElse(max - 1)
}
else orElse(max - 1)
} recoverWith {
case e: Throwable => if (max < 1) fut else orElse(max - 1)
}
}
}

20 changes: 19 additions & 1 deletion core/src/test/scala/RetrySpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package retry

import org.scalatest.FunSpec
import scala.annotation.tailrec
import scala.concurrent.{ Future, Await }
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

Expand Down Expand Up @@ -72,4 +72,22 @@ class RetrySpec extends FunSpec {
"took more time than expected: %s" format took)
}
}

describe("retry.CountingRetry") {
it ("should retry if an exception was thrown") {
import retry.Defaults.timer
implicit val success = new Success[Int](_ == 2)
def fut = () => future { 1 / 0 }
val took = time {
val result = try {
Await.result(retry.Pause(3, 30.millis)(fut),
90.millis + 20.millis)
} catch {
case e: Throwable => e
}
}
assert(took >= 90.millis === true,
"took less time than expected: %s" format took)
}
}
}