Search code examples
scalaretry-logic

How to do a `getOrWaitUntilNonEmpty` as a single liner?


I have a high-level code structure that looks like this:

val block: (=> Option[Seq[String]]) = ...
val matches = block().get.toArray

The problem is that this code may fail i.e. .get being None depending on the time e.g. I'm page-scraping Google too often, then I'd wait and retry ...

I can do the waiting like this i.e. random waits between 11-16s:

val random = new Random()
Thread.sleep((11000 * random.nextFloat() + 6000).ceil.toInt)

What would be an elegant single-liner way to [waiting] loop until the result of executing block isn't empty? Something like:

val timeInMillis = (11000 * random.nextFloat() + 6000).ceil.toInt
block().getOrWaitUntilNonEmpty(timeInMillis).toArray

Solution

  • Try softwaremill/retry like so

    retry.Pause(max = 10, Defaults.delay)(odelay.Timer.default) {
      block
    }
    

    with dependencies

    "com.softwaremill.retry"  %% "retry"       % "0.3.2"
    "com.softwaremill.odelay" %% "odelay-core" % "0.3.0"