Reputation: 41
Earlier I read that creating root(after /user/) actor (system.actorOf) is expensive.
Is there a common pattern to create ClientFactoryActor which main responsibility is simply return new actor on request(for example we need new websocket actor per client etc.)?
Upvotes: 1
Views: 104
Reputation: 2583
Indeed you should try to maintain a hierarchy of actors for the error handling purposes (different supervision strategies) One of the convenient ways to create an actor is to have a companion object that returns a reference to the wanted actor instantiated with the given parameters (singleton factory)
object DemoActor {
/**
* Create Props for an actor of this type.
*
* @param magicNumber The magic number to be passed to this actor’s constructor.
* @return a Props for creating this actor, which can then be further configured
* (e.g. calling `.withDispatcher()` on it)
*/
def props(magicNumber: Int): Props = Props(new DemoActor(magicNumber))
}
class DemoActor(magicNumber: Int) extends Actor {
def receive = {
case x: Int => sender() ! (x + magicNumber)
}
}
class SomeOtherActor extends Actor {
// Props(new DemoActor(42)) would not be safe
context.actorOf(DemoActor.props(42), "demo")
// ...
}
One good starting point is the Akka documentation page.
Upvotes: 1