on demand actor get or else create

后端 未结 4 1889
甜味超标
甜味超标 2020-12-15 05:04

I can create actors with actorOf and look them with actorFor. I now want to get an actor by some id:String and if it doesnt exist, I w

4条回答
  •  时光说笑
    2020-12-15 05:44

    I've not been using akka for that long, but the creator of the actors is by default their supervisor. Hence the parent can listen for their termination;

    var as = Map.empty[String, ActorRef] 
    def getRCActor(id: String) = as get id getOrElse {
      val c = context actorOf Props[RC]
      as += id -> c
      context watch c
      c
    }
    

    But obviously you need to watch for their Termination;

    def receive = {
      case Terminated(ref) => as = as filterNot { case (_, v) => v == ref }
    

    Is that a solution? I must say I didn't completely understand what you meant by "terminated is always true => actor name 1 is not unique!"

提交回复
热议问题