【问题标题】:Akka / Futures - pipe different messages depending on success or failure?Akka / Futures - 根据成功或失败传递不同的消息?
【发布时间】:2017-03-03 15:57:24
【问题描述】:

我在 Actor 上有以下一段代码,我在其中要求其他人执行操作(将某些内容保存在外部数据库中)

如果这成功
然后我向自己发送一条消息,以在我的本地状态中反映该操作的结果,然后将其返回给原始的sender

如果对数据库的持久性失败
然后我想用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 是否有更好的方法来做到这一点?

【问题讨论】:

    标签: scala akka future


    【解决方案1】:

    您可以构建自己的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多