Skip to content

Instantly share code, notes, and snippets.

@jayphelps
Last active August 18, 2022 23:27
Show Gist options
  • Save jayphelps/e46186ddb528d08b19503f09972ffcba to your computer and use it in GitHub Desktop.
Save jayphelps/e46186ddb528d08b19503f09972ffcba to your computer and use it in GitHub Desktop.
Batch Sampling Example from my talk, Real-time Insights, powered by Reactive Programming
let buffer = getWebSocket()
.bufferTime(1000);
let gate = new BehaviorSubject(true);
let batchSize = 50;
let batchSizeCounter = 0;
let results = gate
.switchMap(enabled => enabled ? buffer : Observable.never())
.do(buffer => {
batchSizeCounter += buffer.length;
if (batchSizeCounter >= batchSize) {
// truncates the array, if it's over batchSize
let overage = batchSizeCounter - batchSize;
buffer.length = buffer.length - overage;
// turns on the gate, pausing the stream
gate.next(false);
batchSizeCounter = 0;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment