Skip to content

Instantly share code, notes, and snippets.

@jguix
Last active March 5, 2018 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jguix/993a4c4208f474197997ed26d99cc274 to your computer and use it in GitHub Desktop.
Save jguix/993a4c4208f474197997ed26d99cc274 to your computer and use it in GitHub Desktop.
How to create a recursive observable pipe. Source: http://jsbin.com/finisab/edit?js,console
// A recursive function returning Observable<number>
function recurseToZero(n) {
console.log('B. Entering recursive function for [' + n + '].');
// Once we hit zero, bail out of the recursion. The key to recursion is that
// it stops at some point, and the callstack can be "rolled" back up.
if (n === 0) {
return Rx.Observable.of(0);
}
// Start a NEW PROMISE CHAIN that will become the continuation of the parent
// promise chain. This new promise chain now becomes a completely tangential
// branch to the parent promise chain.
return new Rx.Observable((subscriber) => {
setTimeout(() => {
subscriber.next(n-1);
subscriber.complete();
}, 500);
})
.flatMap(n => {
return recurseToZero(n);
});
}
Rx.Observable.of(null)
.map(() => {
console.group("A. Recursion starts.");
return(3);
})
.flatMap(n => {
// With the recursive function we are creating a totally
// TANGENTIAL BRANCH of the Observable chain.
// --
// A
// |
// B --> B'3 --> B'2 --> B'1 --> B'0
// |
// C
return recurseToZero(n);
})
.subscribe(() => {
console.groupEnd("C. Recursion ended.");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment