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(eitherPipe() 和 to(...)):
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)
}
现在你只需在你的演员中混入MyEitherPipeSupport,你可以这样写:
val result: Future[Either[Int, Throwable]] = Future.successful(Left(5))
eitherPipe(result).to(left, right, anotherOne)