
Extensible implementation of Server-Sent Events enables creating custom stream providers, handling event streams efficiently with features like UTF-8 decoding and connection management.
Extensible Kotlin Multiplatform implementation of Server Sent Events(Sse)
// build.gradle.kts
//...
dependencies {
// stream provider, the SSE event source is a transitive dependency
implementation("cc.scrambledbytes.sse:ktor-stream-provider:1.0.0")
// client engine
implementation("io.ktor:ktor-client-apache5:2.3.0")
}
// in a suspend function
val http = HttpClient()
val provider: SseLineStream.Provider = KtorSseEventStreamProvider(http)
val client = SseEventSource(
url = "https://0.0.0.0:8080/sse",
streamProvider = provider,
)
client.open()
client.events.collect {
println("[Client] Got event: $it")
}You can easily write your own stream provider by implementing the SseLineStream.Provider interface.
An SseLineStream.Provider needs to create a SseLineStream which needs two lambdas:
onClose: which is executed when the connection is closed by the sourceonConnect: which is executed when a connection to the SSE source is being attempted. It passes two callback handles,
onConnect and onLine. onConnect needs to be called exactly once after the connection has been initialized, and
onLine needs to be called everytime a line has arrived in the text stream.In addition to that, a SseLineStream provider should set the following headers/attributes for each connection attempt:
Additional requirements:
onConnect callbackApache 2.0
Extensible Kotlin Multiplatform implementation of Server Sent Events(Sse)
// build.gradle.kts
//...
dependencies {
// stream provider, the SSE event source is a transitive dependency
implementation("cc.scrambledbytes.sse:ktor-stream-provider:1.0.0")
// client engine
implementation("io.ktor:ktor-client-apache5:2.3.0")
}
// in a suspend function
val http = HttpClient()
val provider: SseLineStream.Provider = KtorSseEventStreamProvider(http)
val client = SseEventSource(
url = "https://0.0.0.0:8080/sse",
streamProvider = provider,
)
client.open()
client.events.collect {
println("[Client] Got event: $it")
}You can easily write your own stream provider by implementing the SseLineStream.Provider interface.
An SseLineStream.Provider needs to create a SseLineStream which needs two lambdas:
onClose: which is executed when the connection is closed by the sourceonConnect: which is executed when a connection to the SSE source is being attempted. It passes two callback handles,
onConnect and onLine. onConnect needs to be called exactly once after the connection has been initialized, and
onLine needs to be called everytime a line has arrived in the text stream.In addition to that, a SseLineStream provider should set the following headers/attributes for each connection attempt:
Additional requirements:
onConnect callbackApache 2.0