How do I space out emissions in time?
RxJS offers several throttling and delaying options but not (so far as I have found — hey, it’s a big library!) the simple one: I don’t emissions too close together but if one is early, don’t throw it away, just hold it up for a little while and then emit it in sequence.
I am going to solve this one in pieces. First, I make a function called pause(n) that will return an Observable that is n milliseconds long, but does not emit anything:
function pause(n) {
return timer(n).pipe(filter(() => false));
}
Now let’s extend that with pauseAfter(n, v) that emits v and then pauses n milliseconds:
function pauseAfter(n, v) {
return pause(n).pipe(startWith(v));
}
And finally, there is an operator-factory:
function throttleBuffer(n) {
return concatMap(v => pauseAfter(n, v));
}
The code is here.
The only downside to this technique is that if (as usual) the source Observable emits its final value and completes immediately, the resulting Observable will still run on n more unnecessary milliseconds. I wasn’t able to find a simple way to clip that ending off, but I am not too worried. I don’t believe in using completion as a form of data; it’s literally meant as a signal that the process is complete and can be cleaned up.
Still, if anyone has a suggestion, I’d be glad to hear it.
Next: “How do I get RxViz to display several streams at once?”
I am going to solve this one in pieces. First, I make a function called pause(n) that will return an Observable that is n milliseconds long, but does not emit anything:
function pause(n) {
return timer(n).pipe(filter(() => false));
}
Now let’s extend that with pauseAfter(n, v) that emits v and then pauses n milliseconds:
function pauseAfter(n, v) {
return pause(n).pipe(startWith(v));
}
And finally, there is an operator-factory:
function throttleBuffer(n) {
return concatMap(v => pauseAfter(n, v));
}
The code is here.
The only downside to this technique is that if (as usual) the source Observable emits its final value and completes immediately, the resulting Observable will still run on n more unnecessary milliseconds. I wasn’t able to find a simple way to clip that ending off, but I am not too worried. I don’t believe in using completion as a form of data; it’s literally meant as a signal that the process is complete and can be cleaned up.
Still, if anyone has a suggestion, I’d be glad to hear it.
Next: “How do I get RxViz to display several streams at once?”
Comments
Post a Comment