问题
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-scrapping 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
回答1:
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"
来源:https://stackoverflow.com/questions/56256945/how-to-do-a-getorwaituntilnonempty-as-a-single-liner