0
votes
@GetMapping("/test")
fun fluxTest(): Flux<Int> {
        return Flux.create {em ->
            Thread{
                (0..10).forEach{
                    em.next(it)
                    Thread.sleep(1000)
                }
                em.complete()
            }.run()
        }
    }

So the code above is a Spring MVC controller method to emit 0 ~ 10 numbers at interval of 1 second.

This is my client code.

val client = WebClient.builder().baseUrl("http://localhost:8083/api/v1")
    .build()
val disposable = client.get()
    .uri("/test")
    .retrieve()
    .bodyToFlux(Int::class.java)
    .subscribe ({
        System.out.println("Value arrived : $it")
    }, {err ->
        err.printStackTrace()
    })

The issue is that client program prints out 0~10 at once, rather than one by one at interval of 1 second.

So it doesn't print values from server one by one but print whole received values when stream is completed.

Can anyone help me with this issue?

Thanks

1

1 Answers

2
votes

Looks like you should enable Server-Sent Events, easy way just add producer to the enpoint like this:

@GetMapping(path = "/test", produces=MediaType.TEXT_EVENT_STREAM_VALUE)