What's the Scala way to implement a retry-able call like this one?

前端 未结 14 1729
甜味超标
甜味超标 2020-11-29 16:08

Still the newbie in Scala and I\'m now looking for a way to implement the following code on it:

@Override
public void store(InputStream source, String destin         


        
14条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 16:45

    There is a method in scalaz.concurrent.Task[T]: http://docs.typelevel.org/api/scalaz/nightly/#scalaz.concurrent.Task

    def retry(delays: Seq[Duration], p: (Throwable) ⇒ Boolean = _.isInstanceOf[Exception]): Task[T]
    

    Given a Task[T], you can create a new Task[T] which will retry a certain number of times, where the delay between retries is defined by the delays parameter. e.g.:

    // Task.delay will lazily execute the supplied function when run
    val myTask: Task[String] =
      Task.delay(???)
    
    // Retry four times if myTask throws java.lang.Exception when run
    val retryTask: Task[String] =
      myTask.retry(Seq(20.millis, 50.millis, 100.millis, 5.seconds))
    
    // Run the Task on the current thread to get the result
    val result: String = retryTask.run
    

提交回复
热议问题