Whenever I create an actor that needs some asynchronously obtained data to initialize itself, I find myself using a pattern like this. Does it have a name? (And is it the best way to do it?)
class AsyncInitActor(db: Database, someId: UUID) extends Actor with ActorStash {
case class Initialize(something: Something)
override def preStart() = {
db.getSomething(someId) onSuccess { something =>
self ! Initialize(something)
}
}
def receive = {
case Initialize(something) =>
context become initialized(something)
unstashAll()
case _ => stash()
}
def initialized(something): Receive = {
case whatever =>
}
}
In the case of actors created by cluster sharding, the asynchronous request happens in receive instead of preStart.
Aucun commentaire:
Enregistrer un commentaire