5k7
5k7

Reputation: 107

RxJS - how to emit buffer manually / view elements in buffer

What i'm trying to do is to get numbers of keyboard events if time between these events were less than provided. Maybe that's not correct approach so that's why I'm still in the same place.

So first I made simple stream with filter to catch every events that interest me. Next I made second stream and grouped events into pairs where i can measure time stamps. It seems that it's working pretty good but only with even numbers of events - so after this period of time i need to check if something is in a buffer and if it's there i should add it to my string.

Code :

const timeToWait : number = 500;
const keyDigitsUp$ = Observable.fromEvent(document, "keyup")
  .filter((event:any) => {return ((event.keyCode>=48 && event.keyCode <=57) ||
(event.keyCode>=96 && event.keyCode <=106))});

let bufferedEvents = Observable.from(keyDigitsUp$).bufferCount(2);
let numbers : string = "";

bufferedEvents.subscribe((eventArray) => {
    if (eventArray[1].timeStamp - eventArray[0].timeStamp <= timeToWait)
    {
        numbers+=eventArray[0].key + eventArray[1].key;
    }
    else
    {
        numbers="";
    }
});

Is there any way to make this concept works ? Or maybe there is much better approach which i'm missing. I also made other concepts but they were producing similar results. I can of course make it work in non-reactive way and subscribe to main stream - save last event if exist and than compare it with next and so on, but since i'm trying to learn reactive programming i would like to make it as much reactive as i can.

Upvotes: 2

Views: 320

Answers (1)

Meir
Meir

Reputation: 14365

You're working way too hard :-)

const timeout = 500;

keyDigitsUp$
  .buffer(keyDigitsUp$.debounce(timeout))
  .map(events => (events.length <= 1 ? '' : events.map(event => event.key).join(',')))
  .subscribe(v => console.log('events for timeout ' + timeout + ' msec: '+ v));

See a working jsbin.

The way this works is that it closes the buffer (i.e. produces a chunk) only if any of your keys were not pressed for timeout (500 in this case) mSecs.

I'm not sure what you wanted to do with the key codes, so I just concat them with a comma delimiter.

Note that rxjs 5 syntax might be slightly different.

Upvotes: 1

Related Questions