Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created March 8, 2017 12:29
Show Gist options
  • Save JamieMason/303c5fc90b28c28a804e3f7ea9ab01f1 to your computer and use it in GitHub Desktop.
Save JamieMason/303c5fc90b28c28a804e3f7ea9ab01f1 to your computer and use it in GitHub Desktop.
RxJS: Spread an array over time then reduce when all have been received.
var Rx = require('rxjs');
// values
var letters = 'J,A,M,I,E'.split(',');
var interval = 2000;
// streams
var letters$ = Rx.Observable.from(letters);
var timer$ = Rx.Observable.timer(0, interval);
var lettersOverTime$ = Rx.Observable.zip(letters$, timer$, (item, i) => item);
var eventualWord$ = lettersOverTime$.scan((word, letter) => word + letter, '').last();
// log the next letter every 2 secs
lettersOverTime$.subscribe(console.log);
// log the full word when complete
eventualWord$.subscribe(console.log);
/* output:
*
* lettersOverTime$ : "J"---"A"---"M"---"I"---"E"---|
* eventualWord$ : -------------------------------"JAMIE"|
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment