如何动态调整爆发发射流的去抖动?

时间:2017-07-28 19:09:18

标签: java kotlin rx-java2 rx-kotlin

在发布已缓冲的元素列表之前,我有一个缓冲流,等待预定的静默时间:

INTEGERS
     .share()
     .buffer(INTEGERS.debounce(DEBOUNCE_TIME,TimeUnit.MILLISECONDS,scheduler))
     .map { durations ->
       ... 
     }

我想根据缓冲项目的平均值动态调整DEBOUNCE_TIME,但我很难弄清楚如何实现这一目标。

1 个答案:

答案 0 :(得分:1)

你可以推迟去抖动,取一个项目并在确定新的去抖动值后触发重复:

int DEBOUNCE_TIME = 100;
AtomicInteger debounceTime = new AtomicInteger(DEBOUNCE_TIME);
PublishSubject<Integer> mayRepeat = PublishSubject.create();

AtomicInteger counter = new AtomicInteger();

Observable<Integer> INTEGERS =
        Observable.fromArray(10, 20, 200, 250, 300, 550, 600, 650, 700, 1200)
        .flatMap(v -> Observable.timer(v, TimeUnit.MILLISECONDS)
                .map(w -> counter.incrementAndGet()));

INTEGERS.publish(o ->
        o.buffer(
            Observable.defer(() ->
                o.debounce(
                    debounceTime.get(), TimeUnit.MILLISECONDS)
            )
            .take(1)
            .repeatWhen(v -> v.zipWith(mayRepeat, (a, b) -> b))
        )
    )
    .map(list -> {
        int nextDebounce = Math.min(100, list.size() * 100);
        debounceTime.set(nextDebounce);
        mayRepeat.onNext(1);
        return list;
    })
    .blockingSubscribe(System.out::println);

打印:

[1, 2]
[3, 4, 5]
[6, 7, 8, 9]
[10]