I have a question about Server-Sent Events clients...
# ktor
h
I have a question about Server-Sent Events clients and Kotlin. This is currently how I consume events from my server. 🧵
K 2
This is how I make my SSE call from the client today:
Copy code
private fun listenForEvents(query: String): Flow<EventData> = callbackFlow {
    httpClient.sse(
        urlString = EVENT_URL,
        request = {
            contentType(ContentType.Application.Json)
            parameter("query", query)
        },
    ) {
        incoming.collect { event ->
            event.data?.let {
                Json.decodeFromString<EventData>(it)?.let { eventData ->
                    send(eventData)
                }
            }
        }
    }
}
However, I'm not too fond of doing a
collect()
inside the
callbackFlow {}
, so I'm wondering if there's a way to pass the
incoming
flow back to the caller instead?
s
You probably want to use the
serverSentEventsSession
API which returns a
ClientSSESession
or
ClientSSESessionWithDeserialization
and you can access
incoming
on the returned value.
h
That's what I got there.
httpClient.sse()
gives me a
ClientSSESession
and that's where I do
incoming.collect
. Not sure if this is an issue, but right now I'm doing a
collect()
inside a
callbackFlow
, and I feel there should be a more straightforward way to return
ClientSSESession.incoming
to the caller of
listenForEvents()
.
s
client.sse
takes a lambda for
ClientSSESession
but
client.serverSentEventsSession
returns
ClientSSESession
. Here a complete snippet:
Copy code
val session = httpClient.serverSentEventsSession(urlString = EVENT_URL) {
    contentType(ContentType.Application.Json)
    parameter("query", "...")
}
try {
    session.incoming.collect {  }
} finally {
    session.cancel()
}
I'm not sure if the
try/finally
and
session.cancel()
is actually necessary since a failure in
collect
should cancel the flow, and cancelling the outer
Job
should also cancel the
incoming
but I'd need to test/verify/double-check that 😅
🤔 1
h
Aha.. now I understand. Thanks!
kodee loving 1