即使没有匹配,如何始终在receive()内调用方法

hve*_*iga 4 scala akka

我是Akka/Scala世界的新手.我试图找出当演员收到消息时总是执行某些事情的最佳方式,即使它没有匹配.我知道这receivePartialFunction但我很想知道是否有更好的方法来做到这一点:

def receive: Receive = {
  case string: String => { 
    functionIWantToCall()
    println(string)
  }
  case obj: MyClass => {
    functionIWantToCall()
    doSomethingElse()
  }
  case _ => functionIWantToCall()
}
Run Code Online (Sandbox Code Playgroud)

我非常确定在Scala中有更好的方法来执行此操作,而不是functionIWantToCall()在每个案例中调用.有人可以建议一些东西:)?

Eug*_*nev 7

您可以将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()
  }
Run Code Online (Sandbox Code Playgroud)

或者您可以在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)
Run Code Online (Sandbox Code Playgroud)