Waiting for a client websocket flow to connect before connecting source and sink

老子叫甜甜 提交于 2019-12-06 16:03:32

I found a solution using SourceRef and SinkRef. Although they are meant to be used to bridge the gap between two machines, they can be used here as well.

val webSocketFlow: Flow[Message, Message, Future[WebSocketUpgradeResponse]] =
    Http().webSocketClientFlow(WebSocketRequest(someUrl))

val (sinkRefFuture, sourceRefFuture) =
  StreamRefs.sinkRef[In]()
    .viaMat(f)(Keep.left)
    .toMat(StreamRefs.sourceRef[Out]())(Keep.both)
    .run()

val flow = Flow.fromSinkAndSource(await(sinkRefFuture), await(sourceRefFuture))

with await() being defined for instance like this:

def await[T, F <: T](f: Future[F]): T = Await.result(f, 3.seconds)

That being said, I figured that it is actually better, at least in my case, not to materialize the socket in advance. This way whoever uses it can also take care of reconnecting. I'm now passing around a flow factory that creates new instances of the web socket Flow (may only me materialized once) on demand.

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