How to always call a method inside receive (), even if nothing matches

I am new to the world of Akka / Scala. I'm trying to figure out what is the best way to have something always done when an actor receives a message, even if there is no match for him. I know there receiveis PartialFunction, but I was wondering if there is a better way to do this than:

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

I am sure there is a better way in Scala to do this instead of calling functionIWantToCall()inside each case. Can anyone suggest something :)?

+4
source share
2 answers

You can transfer your receive function to a higher order receive function

  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()
  }

Pipelines 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)
+7

, . :

{
  case _: A =>
    foo()
    a()
  case _: B =>
    foo()
    b()
  case _ =>
    foo()
}

{
  case m =>
    foo()
    m match {
      case _: A =>
        a()
      case _: B =>
        b()
      case _ =>
    }
}
+1

All Articles