2017-01-17 13 views
2

ためPatterns.pipe私はこのような方法があります:アッカ俳優:どちらか一方

def myFuture: Future[Either[MyLeft, MyRight]] = Future { 
. 
. 
. 
} 

私は結果パイプにしたい場合は、私が使用:

Patterns.pipe(myFuture,ec).to(destinationActor) 

しかし、私は、左の場合にしたいです一方のアクターに結果を送信し、他方のアクターに結果を送信する。擬似コードは次のようになります。

MyPatterns.eitherPipe(myFuture,ec).to(leftConsumerActor,rightConsumerActor) 
+0

あなたはこの質問への答えで見たいのですが何か他のものがありますか? – tkachuko

答えて

3

akkaのソースコード自体は、何をすべきかのヒントです。 akka.pattern.PipeToSupportを見て:

def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = { 
    future andThen { 
    case Success(r) ⇒ recipient ! r 
    case Failure(f) ⇒ recipient ! Status.Failure(f) 
    } 
} 

だから私たちは基本的にEitherの派遣と我々の場合のために、このアプローチを再利用することができます

val result: Future[Either[Int, Throwable]] = Future.successful(Left(5)) 
result andThen { 
    case Success(Left(value)) => leftActor ! value 
    case Success(Right(exception)) => rightActor ! exception 
    case Failure(exception) => println("Failure") 
} 

希望DSL達成:

を我々が達成しようとすることができますあなたのDSL(Pipe()to(...))のように:

あなただけで MyEitherPipeSupportを混ぜて、あなたはこのように書くことができ、あなたの俳優で今
trait MyEitherPipeSupport extends PipeToSupport { 

    final class PipeableEitherFuture[L, R](val future: Future[Either[L, R]])(implicit executionContext: ExecutionContext) { 

     def to(leftRef: ActorRef, rightRef: ActorRef, exceptionRef: ActorRef) = future andThen { 
     case Success(Left(value)) ⇒ leftRef ! value 
     case Success(Right(exception)) ⇒ rightRef ! exception 
     case Failure(exception) ⇒ exceptionRef ! Status.Failure(exception) 
     } 
    } 

    implicit def eitherPipe[L, R](future: Future[Either[L, R]])(implicit executionContext: ExecutionContext): PipeableEitherFuture[L, R] = new PipeableEitherFuture(future) 

    } 

val result: Future[Either[Int, Throwable]] = Future.successful(Left(5)) 
    eitherPipe(result).to(left, right, anotherOne) 
0

このような場合は、

myFuture onComplete { 
    case Success(s) => s match { 
     case Right(r) => rightConsumerActor ! r 
     case Left(l) => leftConsumerActor ! l 
    } 
    case Failure(f) => println("failure") 
} 
関連する問題