Emadoo
Emadoo

Reputation: 57

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

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();

}

Upvotes: 3

Views: 2211

Answers (1)

dnault
dnault

Reputation: 8909

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();

Upvotes: 4

Related Questions