Last active
April 26, 2024 07:30
-
-
Save loicdescotte/3914f3fd6513cb85ea1638b60b444f9d to your computer and use it in GitHub Desktop.
Play and Akka Streams source queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Application @Inject() (implicit actorSystem: ActorSystem, exec: ExecutionContext) extends Controller { | |
implicit val materializer = ActorMaterializer() | |
val Tick = "tick" | |
class TickActor(queue: SourceQueue[String]) extends Actor { | |
def receive = { | |
case Tick => queue.offer("tack") | |
} | |
} | |
def queueAction = Action { | |
val (queueSource, futureQueue) = peekMatValue(Source.queue[String](10, OverflowStrategy.fail)) | |
futureQueue.map { queue => | |
val tickActor = actorSystem.actorOf(Props(new TickActor(queue))) | |
val tickSchedule = | |
actorSystem.scheduler.schedule(0 milliseconds, | |
1 second, | |
tickActor, | |
Tick) | |
queue.watchCompletion().map{ done => | |
Logger.debug("Client disconnected") | |
tickSchedule.cancel | |
Logger.debug("Scheduler canceled") | |
} | |
} | |
Ok.chunked( | |
queueSource.map{e => | |
Logger.debug("queue source element : " + e) | |
e | |
} | |
via EventSource.flow | |
) | |
} | |
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much!!