2017-03-03 26 views
1

我有上演员下面的一段代码,我问别人一个动作(坚持的东西在外部DB)Akka /期货 - 根据成功或失败管道不同的消息?

如果是成功
后来我发信息给我以反映我在当地州的行动结果,然后将其返回原始sender

在对持久到DB一个故障的情况下:
后来我想Status.Failure回复(如退还给我)直接到当前的发送者。

的代码看起来是这样的:

case Event(SomeAction(name), _) => 
    val origin = sender() 
    ask(someOtherActor, SomeAction(name)).mapTo[ActionResult] 
    .map(ActionCompleted) 
    .onComplete { 
     case Success(value) => self.tell(value, origin) 
     case Failure(e) => origin ! Status.Failure(e) 
    } 

    stay() 

    case Event(ActionCompleted(result), state) => 
    stay using state.update(result) replying result 

上述工程的代码,但我需要依靠复制发送到一个局部变量,以避免关闭了它。

我想知道是否有更好的方法来做到这一点pipeTo

回答

3

你可以建立你自己的pipeTo,做你所需要的。我认为routeTo将是一个很好的名字。

implicit class RouteTo[A](f: Future[A]) { 
    import akka.pattern.pipe 
    def routeTo(successDestination: ActorRef, 
       failureDestination: ActorRef)(
       implicit sender: ActorRef, 
         ec: ExecutionContext): Unit = 
    f onComplete { 
     case s @ Success(_) => successDestination.tell(s, sender) 
     case f @ Failure(_) => failureDestination.tell(f, sender) 
    } 
} 

import RouteTo._ 
Future("hello").routeTo(successRecipient, failureRecipient)