API that returns a Flux type cannot output in real time in SpringBoot

1 day ago 5
ARTICLE AD BOX

I'm a beginner in SpringBoot, and want to write a demo to test how to use Flux to return data in streaming.

I wrote the following two APIs and tested them using Postman.

The second API (function2) returns one piece of data per second as expected. However, the first API waited for 10 seconds and then received 10 pieces of data all at once. I want to know why this happened.

@PostMapping(value = "/function1", produces = MediaType.TEXT_EVENT_STREAM_VALUE) Flux<Long> function1(){ return Flux.<Long>create(sink -> { for(int i=0;i<10;i++){ sink.next((long)i); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } sink.complete(); }); } @PostMapping(value = "/function2", produces = MediaType.TEXT_EVENT_STREAM_VALUE) Flux<Long> function2(){ return Flux.interval(Duration.ofSeconds(1)).take(10); }
Read Entire Article