我对 Akka/Scala 世界相当陌生。我试图找出在 Actor 接收消息时始终执行某事的最佳方式是什么,即使没有匹配的消息也是如此。我知道 receivePartialFunction 但我想知道是否有比以下更好的方法:

def receive: Receive = {
  case string: String => {
    functionIWantToCall()
    println(string)
  }
  case obj: MyClass => {
    functionIWantToCall()
    doSomethingElse()
  }
  case _ => functionIWantToCall()
}

我很确定 Scala 中有更好的方法来执行此操作,而不是在每种情况下都调用 functionIWantToCall()。有人可以提出一些建议:)?

最佳答案

您可以将 Receive 函数包装在“高阶”Receive 函数中

  def withFunctionToCall(receive: => Receive): Receive = {
    // If underlying Receive is defined for message
    case x if receive.isDefinedAt(x) =>
      functionIWantToCall()
      receive(x)

    // Only if you want to catch all messages
    case _ => functionIWantToCall()
  }

  def receive: Receive = withFunctionToCall {
    case string: String => println(string)
    case obj: MyClass => doSomethingElse()
  }

或者您可以在 Akka 文档中阅读有关管道的信息:http://doc.akka.io/docs/akka/snapshot/contrib/receive-pipeline.html

我认为这正是您解决此类问题所需要的
  val callBefore: Receive => Receive =
    inner ⇒ {
      case x ⇒ functionIWantToCall; inner(x)
    }

  val myReceive: Receive = {
    case string: String => println(string)
    case obj: MyClass => doSomethingElse()
  }

  def receive: Receive = callBefore(myReceive)

10-08 19:03