Created
March 8, 2017 12:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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