I want to debounce a stream of values, and add a flush signal to it. When the flush signal comes, debounce should immediately emit its last received value and clear its buffer. If there is no value in debounce's buffer, the flush signal does nothing. Basically, the flush signal temporarily sets the debounce time to 0:
values: -- 1 -- 2 -- 3 ---------- 4 -- 5 -- 6 --------------------
flush: --------------------------------- * -------------- * -----
output: ------------------- 3 ----------- 5 ------- 6 ------------
I tried the following approach, mimicking debounce
with delay
and switchToLatest
, but couldn't figure out how to do flushedValues
, which should emit the last value, if any, that comes within 2 seconds before a flush signal.
// valuesSubject: Publisher<Int, Never> is the value stream
// flushSubject: Publisher<Void, Never> is the flush stream
let valuesWithDelay = valuesSubject.map { $0.delay(for: 2, scheduler: ...) }
let flushedValues = // somehow combine valuesSubject and flushSubject
let output = Publishers.Merge(valuesWithDelay, flushedValues).switchToLatest()