3

First time using WebFlux, Flux, reactive, etc. I've got a simple server setup to GET, POST, PUT, DELETE a Message. I'd like to emit a value over a server sent event flux as soon as the server router receives a POST.

fun router() = router {
    accept(TEXT_EVENT_STREAM).nest {
        GET("/messages/events", messageHandler::showLastMessage)
    }
    "/".nest {
        (accept(APPLICATION_JSON) and "/messages").nest {
            GET("/", messageHandler::getMessages)
            POST("/", messageHandler::addMessage)
            GET("/{id}", messageHandler::getMessage)
            PUT("/{id}", messageHandler::updateMessage)
            DELETE("/{id}", messageHandler::deleteMessage)
        }
    }
    resources("/**", ClassPathResource("static/"))
}.filter { request, next ->
    next.handle(request).flatMap {
        if (it is RenderingResponse) RenderingResponse.from(it).modelAttributes(attributes(request.locale(), messageSource)).build() else it.toMono()
    }
}

In this example, /messages/events just repeats the entire collection (because I don't know what I'm doing)

val lastMessage = Flux.just(messageMap.values)

val lastMessageStream = Flux
        .zip(Flux.interval(Duration.ofMillis(1000)), lastMessage.repeat())

fun showLastMessage(req: ServerRequest) =
        ok().bodyToServerSentEvents(lastMessageStream)

My questions are (i think):

Is it possible to emit from a Flux, similar to interval(), but ONLY when a collection changes, or something triggers the Flux to emit? In other words:

Flux.wheneverIgetSomething(thatSomething)
Lou Morda
  • 5,078
  • 2
  • 44
  • 49

0 Answers0