javascript - RxJS: Debounce with regular sampling -


i have observable emits stream of values user input (offset values of slider).

i want debounce stream, while user busy sliding, emit value if nothing has come through for, 100ms, avoid being flooded values. want emit value every 1 second if endlessly debouncing (user sliding , forth continuously). once user stops sliding though, want final value debounced stream.

so want combine debounce regular "sampling" of stream. right setup this:

const debounce$ = slider$.debouncetime(100),       sampler$ = slider$.audittime(1000);  debounce$     .merge(sampler$)     .subscribe((value) => console.log(value)); 

assuming user moves slider 2.4 seconds, emits values follows:

 start                      end   (x)---------|---------|---(x)|----|               |         |      |    |              1.0       2.0    2.5  3.0  <-- unwanted value @ end               ^         ^      ^             sample   sample   debounce  <-- these 

i don't want value emitted @ 3 seconds (from sampler$ stream).

obviously merge wrong way combine these 2 streams, can't figure out combination of switch, race, window or whatever use here.

you can solve problem composing observable serves signal, indicating whether or not user sliding. should it:

const sliding$ = slider$.mapto(true).merge(debounce$.mapto(false)); 

and can use control whether or not sampler$ emits value.

a working example:

const since = date.now();  const slider$ = new rx.subject();    const debounce$ = slider$.debouncetime(100);  const sliding$ = slider$.mapto(true).merge(debounce$.mapto(false));    const sampler$ = slider$    .audittime(1000)    .withlatestfrom(sliding$)    .filter(([value, sliding]) => sliding)    .map(([value]) => value);    debounce$    .merge(sampler$)    .subscribe(value => console.log(`${time()}: ${value}`));    // simulate sliding:    let value = 0;  (let = 0; <= 2400; += 10) {    value += math.random() > 0.5 ? 1 : -1;    slide(value, i);  }    function slide(value, at) {    settimeout(() => slider$.next(value), at);  }    function time() {    return `t+${((date.now() - since) / 1000).tofixed(3)}`;  }
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/rx.min.js"></script>


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -