Search code examples
scalaakkaactor

How to terminate processing within actor receive?


I am currently having some huge if blocks within the receive methods of my akka actors. Example:

def receive = {
  case Alarm(msg) => 
    if (msg != null) {
      [... huge amount of code ...]
    } else {
      logger.log("false alarm")
    }
}

Since I think this is not the best readable code, I was wondering if I can do something like that.

def receive = {
  case Alarm(msg) =>
    if (msg == null) {
      logger.log("false alarm")
      break // ????? (I know this does not work, but what else?)
    }
    [... huge amount of code ...]
}

Any suggestions or best practices?

Edit: Okay I see I have to be more precise. I am having a lot of database queries within the huge amount of code block and dont want to wrap ALL those into an if else construct.

Edit2: The thing is, that my actor needs to do a bunch of database operations and that it needs to ensure that each dataset is present before it can process it. I have to do this due to robustness requirements.


Solution

  • Either have if-elses like you already have, or divide it up into different cases:

    def receive = {
      case Alarm(msg) => 
        if (msg != null) {
          [... huge amount of code ...]
        } else {
          logger.log("false alarm")
        }
    }
    

    becomes

    def receive = {
      csae Alarm(null) => logger.log("false alarm")
      case Alarm(msg) => [... huge amount of code ...]
    }