如何使用Reactive Extensions按空闲时段对事件进行分组

Mat*_*ell 4 rx-java

我有一个问题,Reactive Extensions似乎特别适合.我有一个事件源,它在短时间内创建事件,中间有相对较长的空闲时间.我想分批对这些事件进行分组,其中(理想情况下)每一系列事件最终会在一批中结束.使用RxJava,有一个很好的方法吗?Observable.buffer(Observable)Observable.buffer(Func0)似乎很有希望,但可以使用Observable.window()或Observable.groupByUntil().

小智 16

以下代码似乎适用于去抖缓冲区:

import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

public class DebounceBuffer {

    public static void main(String args[]) {
        // see all bursts in a single sequence
        //        intermittentBursts().toBlocking().forEach(System.out::println);

        // debounce to the last value in each burst
        //        intermittentBursts().debounce(10, TimeUnit.MILLISECONDS).toBlocking().forEach(System.out::println);

        /* The following will emit a buffered list as it is debounced */
        // first we multicast the stream ... using refCount so it handles the subscribe/unsubscribe
        Observable<Integer> burstStream = intermittentBursts().publish().refCount();
        // then we get the debounced version
        Observable<Integer> debounced = burstStream.debounce(10, TimeUnit.MILLISECONDS);
        // then the buffered one that uses the debounced stream to demark window start/stop
        Observable<List<Integer>> buffered = burstStream.buffer(debounced);
        // then we subscribe to the buffered stream so it does what we want
        buffered.take(20).toBlocking().forEach(System.out::println);
    }

    public static Observable<Integer> intermittentBursts() {
        return Observable.create((Subscriber<? super Integer> s) -> {
            while (!s.isUnsubscribed()) {
                // burst some number of items
                for (int i = 0; i < Math.random() * 20; i++) {
                    s.onNext(i);
                }
                try {
                    // sleep for a random amount of time
                    Thread.sleep((long) (Math.random() * 1000));
                } catch (Exception e) {
                    // do nothing
                }
            }
        }).subscribeOn(Schedulers.newThread()); // use newThread since we are using sleep to block
    }

}
Run Code Online (Sandbox Code Playgroud)

它发出以下内容:

[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1]
[0, 1, 2, 3, 4, 5]
[0, 1, 2]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3]
[0]
[0, 1, 2]
[0]
Run Code Online (Sandbox Code Playgroud)