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

前端 未结 14 1734
甜味超标
甜味超标 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:46

    //Here is one using Play framework
    
    def retry[T](times:Int)(block: => Future[T])(implicit ctx: ExecutionContext):Future[T] = {
    
    type V = Either[Throwable,T]
    val i:Iterator[Future[Option[V]]] = 
      Iterator.continually(block.map(t => Right(t)).recover { case e => Left(e) }.map(t => Some(t)))
    def _retry:Iteratee[V,V] = {
        def step(ctr:Int)(i:Input[V]):Iteratee[V,V] = i match {
            case Input.El(e) if (e.isRight) => Done(e,Input.EOF)
            case _ if (ctr < times) => Cont[V,V](i => step(ctr + 1)(i))
            case Input.El(e) => Done(e,Input.EOF)
        }
        Cont[V,V](i => step(0)(i))
    }
    Enumerator.generateM(i.next).run(_retry).flatMap { _ match {
      case Right(t) => future(t)
      case Left(e) => Future.failed(e)
    }}
    }
    

提交回复
热议问题