How to stop execution a Flux after a certain time in Java?

Viewed 933

How can the publishing(Streaming) in Flux be stopped After timer e.g. 1s, if there are still numbers, they will not be published. e.g. after 1000 numbers, then they will not be printed.

@Test
public void test() {    
        
        Flux.range(0, 20000)
            // hier 
            .delayElements(Duration.ofMillis(1))
            .parallel(2)
            .runOn(Schedulers.parallel())
            .doOnNext(i -> {
                System.out.println(i);

            })
            .sequential()
            .blockLast();

}
1 Answers

You can use Flux.take(Duration) to cause the Flux to complete after a certain duration.

For the code you posted, and a threshold of 1 second, that would look like this:

Flux.range(0, 20000)
    // hier 
    .delayElements(Duration.ofMillis(1))
    .parallel(2)
    .runOn(Schedulers.parallel())
    .doOnNext(i -> {
        System.out.println(i);
    })
    .sequential()
    .take(Duration.ofSeconds(1)) // <--
    .blockLast();
Related