Mahdi
Mahdi

Reputation: 1852

Create an actor if it does not exists in scala akka cannot find the actor

Based on this solution I have implemented the following, but it throws an exception saying that the actor with that name already exists:

    implicit val timeout = Timeout(5 seconds)
    val pathToLookup: String = self.path.toString + "/" + actorName

    context.actorSelection(pathToLookup).resolveOne().onComplete(useActor)
    def useActor(possible: Try[ActorRef]) = {
      val definite = possible match {
        case Success(actor) =>
          log.debug("Found an actor " + actorName)
          actor
        case Failure(_) =>
          log.debug("Creating a new actor " + actorName)
          context.actorOf(Props[MyActor], name = actorName)
      }
      // other code
    }

I have a feeling that I am not passing the right path to actorSelection but I do not see how to fix it.

Edit: I corrected the path of the child actor, and it still does not find the actor. I also tried toStringWithoutAddress but it does not work either.

Upvotes: 0

Views: 1153

Answers (1)

johanandren
johanandren

Reputation: 11479

ActorySystem.actorOf(props) creates top level actors, that will be directly under /user/ while context.actorOf(props) inside of an actor creates actors as children of that actor so they will have the path /user/path/to/parent/child.

The problem is that you are looking for the actors under /user/[name] but you are creating them as children of your current actor, so they will be at something like /user/myactor/[name].

Also note, that you are closing over actor state and using internal actor things from a different thread which is unsafe when you are using onComplete and context like that. See the warning in this section about that: http://doc.akka.io/docs/akka/2.4.1/scala/actors.html#Ask__Send-And-Receive-Future

Upvotes: 1

Related Questions