SSE

fun HttpClientConfig<*>.SSE(config: SSEConfig.() -> Unit)

Installs the SSE plugin using the config as configuration.

Example of usage:

val client = HttpClient() {
    SSE {
        showCommentEvents()
        showRetryEvents()
    }
}

Report a problem


Client Server-Sent Events (SSE) plugin that allows you to establish an SSE connection to a server and receive Server-Sent Events from it. For a simple session, use ClientSSESession. For a session with deserialization, use ClientSSESessionWithDeserialization.

val client = HttpClient {
    install(SSE)
}

// SSE request
client.serverSentEvents("http://localhost:8080/sse") { // `this` is `ClientSSESession`
    incoming.collect { event ->
        println("Id: ${event.id}")
        println("Event: ${event.event}")
        println("Data: ${event.data}")
    }
}

// SSE request with deserialization
client.sse({
    url("http://localhost:8080/serverSentEvents")
}, deserialize = {
    typeInfo, jsonString ->
    val serializer = Json.serializersModule.serializer(typeInfo.kotlinType!!)
    Json.decodeFromString(serializer, jsonString)!!
}) { // `this` is `ClientSSESessionWithDeserialization`
    incoming.collect { event: TypedServerSentEvent<String> ->
        when (event.event) {
            "customer" -> {
                val customer: Customer? = deserialize<Customer>(event.data)
            }
            "product" -> {
                val product: Product? = deserialize<Product>(event.data)
            }
        }
    }
}

To learn more, see the SSE and the SSE specification.

Report a problem