6

For my actor hierarchy, I do not know all the actors I need until I process the data through a few actors, so I'm looking for a way to either return an existing ActorRef or create a new action. This is what I would like the code below to either create an actor if one does not exist at "my-id-1" or return the one that already exists.

Context.ActorOf(MyActor.Props(message), "my-id-1");

The above code will (as documented) throw a InvalidActorNameException if the actor already exists. How can I accomplish this in Akka.net?

Zeus82
  • 6,065
  • 9
  • 53
  • 77

1 Answers1

14

You can check if current actor has a child with provided name by using Context.Child(actorName) method. It will return actor ref of the target actor if it exists or ActorRefs.Nobody if there is no such actor.

Code in your case could look like:

var child = Context.Child(actorName);
if (Equals(child, ActorRefs.Nobody))
    child = Context.ActorOf(MyActor.Props(message), actorName);
Bartosz Sypytkowski
  • 7,463
  • 19
  • 36
  • What if the actor I want is not a child? – Zeus82 Oct 12 '16 at 18:27
  • You can find any actor by using `Context.ActorSelection` method. However only parents are able to create their children. In this case you'd need to enhance the parent with behavior allowing it to handle an arbitrary request to get or create an actor. Similar concept has been implemented as part of [Akka.Cluster.Sharding](http://getakka.net/docs/clustering/cluster-sharding) module. – Bartosz Sypytkowski Oct 13 '16 at 06:26