Skip to content

Instantly share code, notes, and snippets.

@senthilnathansk
Forked from jooyunghan/async-gen.js
Created January 31, 2018 03:12
Show Gist options
  • Select an option

  • Save senthilnathansk/8df9bd3febe0fdc5cba0fc34f0371d6c to your computer and use it in GitHub Desktop.

Select an option

Save senthilnathansk/8df9bd3febe0fdc5cba0fc34f0371d6c to your computer and use it in GitHub Desktop.
import { Observable } from "rxjs";
Observable.prototype[Symbol.asyncIterator] = createAsyncIterator;
async function* createAsyncIterator() {
const promise = [];
const values = [];
let done = false;
let error = null;
const subscription = this.subscribe({
next(value) {
values.push(value);
promise.splice(0).forEach(r => r());
},
error(err) {
error = err;
promise.splice(0).forEach(r => r());
},
complete() {
done = true;
promise.splice(0).forEach(r => r());
},
});
try {
while (true) {
while (values.length > 0) yield values.shift();
if (error) throw error;
if (done) break;
await new Promise(r => promise.push(r));
}
} finally {
subscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment