How to use an Akka Streams SourceQueue with PlayFramework

前端 未结 2 1864
清歌不尽
清歌不尽 2020-12-13 10:25

I would like to use a SourceQueue to push elements dynamically into an Akka Stream source. Play controller needs a Source to be able to stream a result using the chunc

2条回答
  •  春和景丽
    2020-12-13 11:08

    The solution is to use mapMaterializedValue on the source to get a future of its queue materialization :

    def sourceQueueAction = Action {
        val (queueSource, futureQueue) = peekMatValue(Source.queue[String](10, OverflowStrategy.fail))
    
        futureQueue.map { queue =>
          Source.tick(0.second, 1.second, "tick")
            .runForeach (t => queue.offer(t))
        }
        Ok.chunked(queueSource)
    
      }
    
      //T is the source type, here String
      //M is the materialization type, here a SourceQueue[String]
      def peekMatValue[T, M](src: Source[T, M]): (Source[T, M], Future[M]) = {
        val p = Promise[M]
        val s = src.mapMaterializedValue { m =>
          p.trySuccess(m)
          m
        }
        (s, p.future)
      }
    

提交回复
热议问题