Search code examples
scalaakkaakka-typed

What is the difference between Behaviors.setup and Behaviors.receive in Akka Typed?


In the Akka tutorials i sometimes see

Behaviors.setup { ctx =>
 ...

 Behaviors.receiveMessage[String] { msg =>
  ... // some operations with ctx and message  
 }

}

and sometimes just

Behaviors.receive[String] { (ctx , msg) =>
  ... // some operations with ctx and message  
}

What is the difference?


Solution

  • The function (ActorContext[String] => Behavior[String]) passed to Behaviors.setup is executed when the actor is spawned, regardless of whether there's a message to process.

    The function ((ActorContext[String], String) => Behavior[String]) passed to Behaviors.receive is not executed until there's a message to process.

    Note that if you had

    Behaviors.setup { ctx =>
      // code block A
    
      Behaviors.receiveMessage[String] { msg =>
        // code block B
      }
    }
    
    Behaviors.receive[String] { (ctx, msg) =>
      // code block A
      // code block B
    }
    

    code block A in the Behaviors.receive would execute with every message (unless and until a new Behavior was installed by code block B).