Skip to content

Instantly share code, notes, and snippets.

@PyroSA
Last active February 21, 2017 21:28
Show Gist options
  • Save PyroSA/6d0485eeeec56db1d754a75c1360e21f to your computer and use it in GitHub Desktop.
Save PyroSA/6d0485eeeec56db1d754a75c1360e21f to your computer and use it in GitHub Desktop.
RxJs Observable to run a series of promises in series with no concurrency
const Rx = require('rxjs'); // Did this in node using `npm install rxjs`
// -- Our fake async function
const fakeAsync = (input) => {
return new Promise((resolve, reject) => {
console.log(`Start: ${input}`);
setTimeout(() => {
console.log(`Finish: ${input}`);
resolve(`Processed ${input}`);
}, Math.random()*1500+100);
})
};
// -- Our observable Subject and Suscriber
var subject = new Rx.Subject();
var subscription = subject
.concatMap((item) => fakeAsync(item))
.subscribe(
(item) => console.log('Done: %s', item),
(error) => console.log('Error: %s', error),
() => console.log('Completed')
);
// --- Create 10 jobs over first 3 seconds
for (var fileIndex = 0; fileIndex < 10; fileIndex ++) {
setTimeout((index) => {
console.log(`Add: ${index}`);
subject.next(index);
}, 300 * fileIndex, fileIndex);
}
// --- Create 5 jobs a little after 5 seconds (while batch 1 is busy)
for (var fileIndex = 10; fileIndex < 15; fileIndex ++) {
setTimeout((index) => {
console.log(`Add: ${index}`);
subject.next(index);
}, 5000, fileIndex);
}
// --- Create 5 jobs a little after 15 seconds (after other batches)
for (var fileIndex = 20; fileIndex < 25; fileIndex ++) {
setTimeout((index) => {
console.log(`Add: ${index}`);
subject.next(index);
}, 15000, fileIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment