在发布已缓冲的元素列表之前,我有一个缓冲流,等待预定量的静默时间:
INTEGERS
.share()
.buffer(INTEGERS.debounce(DEBOUNCE_TIME,TimeUnit.MILLISECONDS,scheduler))
.map { durations ->
...
}
我想DEBOUNCE_TIME
根据缓冲项目的平均值进行动态调整,但我很难弄清楚如何实现这一点。
一旦确定了新的去抖值,您可以推迟去抖,取其中一项并触发重复:
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]