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

≯℡__Kan透↙ 提交于 2019-12-13 15:10:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!