Search code examples
javaakkaakka-actor

Can ActorContext (getContext()) be passed outside the Actor to create child actors?


I want to have an ActorFactory class as below

public class SampleActorFactory {
  // Simple create method
  public createActor(AbstractActor.ActorContext actorContext, Props props) {
     return actorContext.actorOf(props);
  }
 // other complex create methods
 ...
}

Is it ok to create a child actor using the above factory class, or is this considered a bad practice? If considered bad practice, then why?

eg:

public class SampleActor extends AbstractActor {
 private final SampleActorFactory sampleActorFactory;
 @Override 
 public Receive createReceive() {
        return receiveBuilder()
            .match(SampleData.class, sampleData -> {
              Props sampleProps = getSampleProps(...);
              ActorRef childActor = sampleActorFactory.createActor(getContext(), sampleProps);
            })
            .build();

    }
}

Solution

  • I don't see anything wrong with that approach, you should be able to access context outside of actor system. But.... generally to create an actor, you just need one line of code as below. With your code, you have to write two lines of code (one for Props and other one to call your createActor() method) where ever you create an actor. Other than implementing a factory method, if you achieve any additional benefit from it, you can go for it.

    ActorRef demoActor = getContext().system().actorOf(Props.create(MyDemoActor.class, prop1, prop2);