简体   繁体   中英

How to collect values over a period of time with max count from a signal?

Is there a way to collect values over a period of time with max count from a signal? It seems like a combination of collect(every:on:skipEmpty:discardWhenCompleted:) and collect(count:) . The resulting signal would send an event at interval seconds apart if the count of accumulated values doesn't reach max count during time interval. Otherwise, it will send immediately.

Question is hard to grasp, but I will try.

If you want to batch emitted values by count and time, you can use bufferTimeout method. See documentation here https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#bufferTimeout-int-java.time.Duration-

Some example:

void bufferTimeoutTry() throws InterruptedException {
    Flux.interval(Duration.ofMillis(157))
            .filter(time -> time > 20 && time < 38 || time % 5 == 0 || time % 17 == 0)
            .bufferTimeout(5, Duration.ofSeconds(1))
            .doOnNext(list -> {
                // we will get list of items buffered in 1-second period of time, or at most 5 items.
            })
            .subscribe(System.out::println);
    Thread.sleep(30000);
}

Output will be list of items. Flux.interval is generating sequential long number (ie 1, 2, 3, 4, 5, ...), it is filtered on second line of method (to get some non interval behavior) and than buffer-ed. After buffer, there is no long on stream, but it has changed to list of longs.

[0, 5]
[10, 15]
[17, 20, 21, 22, 23]
[24, 25, 26, 27, 28]
[29, 30, 31, 32, 33]
[34, 35, 36, 37, 40]
[45, 50, 51]
[55, 60]
[65, 68, 70]
[75, 80]
[85, 90]
[95, 100]
[102, 105]
[110, 115]
[119, 120, 125]
[130, 135, 136]
[140, 145]
[150, 153, 155]
[160, 165]
[170, 175]
[180, 185]

Is this what you want?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM