2

I want to do some server-side events (SSE) to a web app. I think I have all the SSE plumbing up and going. I now need to create a Source on the Akka HTTP side of the house.

I found you can do something like this:

val source = Source.actorRef(5, akka.stream.OverflowStrategy.dropTail)

What I want to do is somehow "publish" to this source, presumably by sending an actor a message. I see from the docs that this call creates Source<T,ActorRef>.

How can I get this ActorRef instance so I can send messages to it?

Greg
  • 10,696
  • 22
  • 68
  • 98
  • Did you use https://developer.lightbend.com/docs/alpakka/current/sse.html or are you writing this infrastructure yourself? – Arnout Engelen Nov 06 '17 at 13:37
  • Writing myself for this example. Thanks for the link tho! If my exercise goes well the grown-up version may well need something like this. – Greg Nov 06 '17 at 17:54
  • Possible duplicate of [Accessing the underlying ActorRef of an akka stream Source created by Source.actorRef](https://stackoverflow.com/questions/30785011/accessing-the-underlying-actorref-of-an-akka-stream-source-created-by-source-act) – Ramón J Romero y Vigil Jan 08 '19 at 16:21

1 Answers1

2

To obtain the materialized ActorRef from Source.actorRef, the stream has to be running. For example, let's say that you want to send the SSE payload data (in the form of a String) to this actor, which converts that data to ServerSentEvent objects to send to the client. You could do something like:

val (actor, sseSource) =
  Source.actorRef[String](5, akka.stream.OverflowStrategy.dropTail)
        .map(s => /* convert String to ServerSideEvent */)
        .keepAlive(1.second, () => ServerSentEvent.heartbeat)
        .toMat(BroadcastHub.sink[ServerSentEvent])(Keep.both)
        .run()

// (ActorRef, Source[ServerSentEvent, NotUsed])

Now you can send messages to the materialized actor:

actor ! "quesadilla"

And use sseSource in your route:

path("events") {
  get {
    complete(sseSource)
  }
}

Note that there is no backpressure with this approach (i.e., messages to the actor are fired-and-forgotten).

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54