Initializing an actor before being able to handle some other messages

前端 未结 2 393
野趣味
野趣味 2021-01-12 08:07

I have an actor which creates another one:

class MyActor1 extends Actor {
  val a2 = system actorOf Props(new MyActor(123))
}

The second ac

2条回答
  •  隐瞒了意图╮
    2021-01-12 08:35

    You could use become method to change actor's behavior after initialization:

    class MyActor2(a: Int) extends Actor {
    
      server ! GetInitializationData
    
      def initialize(d: InitializationData) = ???
    
      //handle incoming messages
      val initialized: Receive = {
        case "job1" => // do some job but after it's initialized (bootstrapped) itself
      }
    
      def receive = {
        case d @ InitializationData =>
          initialize(d)
          context become initialized
      }
    }
    

    Note that such actor will drop all messages before initialization. You'll have to preserve these messages manually, for instance using Stash:

    class MyActor2(a: Int) extends Actor with Stash {
    
      ...
    
      def receive = {
        case d @ InitializationData =>
          initialize(d)
          unstashAll()
          context become initialized
        case _ => stash()
      }
    }
    

    If you don't want to use var for initialization you could create initialized behavior using InitializationData like this:

    class MyActor2(a: Int) extends Actor {
    
      server ! GetInitializationData
    
      //handle incoming messages
      def initialized(intValue: Int, strValue: String): Receive = {
        case "job1" => // use `intValue` and `strValue` here
      }
    
      def receive = {
        case InitializationData(intValue, strValue) =>
          context become initialized(intValue, strValue)
      }
    }
    

提交回复
热议问题