How to get an actor reference (ActorRef) from ActorFlow?

非 Y 不嫁゛ 提交于 2021-02-08 02:21:18

问题


According to the Play documentation on WebSockets the standard way to establish a WebSocket is to use ActorFlow.actorRef, which takes a function returning the Props of my actor. My goal is to get a reference to this underlying ActorRef, for instance in order to send a first message or to pass the ActorRef to another actor's constructor.

In terms of the minimal example from the documentation, I'm trying to achieve this:

class WebSocketController @Inject() (implicit system: ActorSystem, materializer: Materializer) {

  def socket = WebSocket.accept[String, String] { request =>
    val flow = ActorFlow.actorRef { out => MyWebSocketActor.props(out) }
    // How to get the ActorRef that is created by MyWebSocketActor.props(out)?
    // Fictitious syntax (does not work)
    flow.underlyingActor ! "first message send"
    flow
  }
}

How can I get a reference to the actor that is created?

If it is not possible to get an ActorRef at this point (does it require materialization of the flow?), what would be the easiest way to store a reference to the created actor?


回答1:


Using Actor.preStart() hook you can do some tricks to access the actorRef:

class MyWebSocketActor(
  out: ActorRef, 
  firstMessage: Any, 
  actorRegistry: ActorRef
) extends Actor {
  import play.api.libs.json.JsValue
  override def preStart(): Unit = {
    self ! firstMessage
    actorRegistry ! self
  }
  ...
}

def socket = WebSocket.accept[String, String] { request =>
  ActorFlow.actorRef { out => 
    Props(new MyWebSocketActor(out, "First Message", someRegistryActorRef)) 
  }
}


来源:https://stackoverflow.com/questions/42923671/how-to-get-an-actor-reference-actorref-from-actorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!