Last active
September 7, 2017 19:51
-
-
Save shairontoledo/7082c24f4e1b331f3c02efe747fd8733 to your computer and use it in GitHub Desktop.
RxJS Async mapping
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
const getTokens = (ids) => { | |
return Rx.Observable.create((observer) => { | |
ids.forEach((id) => { | |
setTimeout(() => observer.next(`Token of id: ${id}`), 1000) | |
}) | |
setTimeout(() => { | |
console.log("Got tokens") | |
observer.complete() | |
}, 7000) | |
}) | |
} | |
const users = Rx.Observable.create((observer) => { | |
observer.next({ name: 'user1', id: 1 }) | |
setTimeout(() => observer.next({ name: 'user2', id: 2 }), 1000) | |
setTimeout(() => observer.next({ name: 'user3', id: 3 }), 2000) | |
setTimeout(() => observer.complete(), 4000) | |
}) | |
users | |
.map((user) => { | |
console.log('Got user: ' + JSON.stringify(user)) | |
return user.id | |
}) | |
.toArray() | |
.mergeMap(ids => getTokens(ids)) | |
.toArray() | |
.subscribe(tokens => console.log('All tokens here: ' + JSON.stringify(tokens))) | |
// Expected output | |
// [ 'Token of id: 1', 'Token of id: 2', 'Token of id: 3' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simulation: