Akka演员无法发回消息

时间:2015-01-29 09:35:39

标签: scala akka actor

说,我有一个接收功能喜欢的演员

def receive = {
  case Message =>
    val doFuture: Future[String] = doSomething()

    doFuture onSuccess {
      case doResult =>
        //////////// Here is the problem !! /////////////
        // --> here fail. Seems sender cannot send back the result to the caller
        sender ! doResult
    }

    doFuture onFailure {
      // handle exception
    }
}

为什么发件人不能再发回邮件?

2 个答案:

答案 0 :(得分:2)

def receive = {
  case Message =>
    val doFuture: Future[String] = doSomething()
    val requester = sender

    doFuture onSuccess {
      case doResult =>
        requester ! doResult
    }

    doFuture onFailure {
      // handle exception
    }
}

您可以保存原始发件人,然后使用它(如果您出于某种原因不想使用管道)。无论如何,管道看起来好多了,专门为这种情况设计:

import akka.pattern.pipe

 def receive = {
      case Message =>
          val doFuture: Future[String] = doSomething()  
          doFuture pipeTo sender
 }

答案 1 :(得分:2)

这是pipeTo的用途:

import akka.pattern.pipe

...

doFuture.pipeTo(sender())