Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created December 21, 2017 09:23
Show Gist options
  • Save jooyunghan/90bfe42ac1ec7a3866e07a59cbcc515e to your computer and use it in GitHub Desktop.
Save jooyunghan/90bfe42ac1ec7a3866e07a59cbcc515e 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