-
Notifications
You must be signed in to change notification settings - Fork 3k
feat(Observable): now implements Symbol.asyncIterator
#7189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -347,4 +347,126 @@ export class Observable<T> implements Subscribable<T> { | |
pipe(...operations: OperatorFunction<any, any>[]): Observable<any> { | ||
return pipeFromArray(operations)(this); | ||
} | ||
|
||
/** | ||
* Observable is async iterable, so it can be used in `for await` loop. This method | ||
* of subscription is cancellable by breaking the for await loop. Although it's not | ||
* recommended to use Observable's AsyncIterable contract outside of `for await`, if | ||
* you're consuming the Observable as an AsyncIterable, and you're _not_ using `for await`, | ||
* you can use the `throw` or `return` methods on the `AsyncGenerator` we return to | ||
* cancel the subscription. Note that the subscription to the observable does not start | ||
* until the first value is requested from the AsyncIterable. | ||
* | ||
* Functionally, this is equivalent to using a {@link concatMap} with an `async` function. | ||
* That means that while the body of the `for await` loop is executing, any values that arrive | ||
* from the observable source will be queued up, so they can be processed by the `for await` | ||
* loop in order. So, like {@link concatMap} it's important to understand the speed your | ||
* source emits at, and the speed of the body of your `for await` loop. | ||
* | ||
* ## Example | ||
* | ||
* ```ts | ||
* import { interval } from 'rxjs'; | ||
* | ||
* async function main() { | ||
* // Subscribe to the observable using for await. | ||
* for await (const value of interval(1000)) { | ||
* console.log(value); | ||
* | ||
* if (value > 5) { | ||
* // Unsubscribe from the interval if we get a value greater than 5 | ||
* break; | ||
* } | ||
* } | ||
* } | ||
* | ||
* main(); | ||
* ``` | ||
*/ | ||
[Symbol.asyncIterator](): AsyncGenerator<T, void, void> { | ||
let subscription: Subscription | undefined; | ||
let hasError = false; | ||
let error: unknown; | ||
let completed = false; | ||
const values: T[] = []; | ||
const deferreds: [(value: IteratorResult<T>) => void, (reason: unknown) => void][] = []; | ||
|
||
const handleError = (err: unknown) => { | ||
hasError = true; | ||
error = err; | ||
while (deferreds.length) { | ||
const [_, reject] = deferreds.shift()!; | ||
reject(err); | ||
} | ||
}; | ||
|
||
const handleComplete = () => { | ||
completed = true; | ||
while (deferreds.length) { | ||
const [resolve] = deferreds.shift()!; | ||
resolve({ value: undefined, done: true }); | ||
} | ||
}; | ||
|
||
return { | ||
benlesh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
next: (): Promise<IteratorResult<T>> => { | ||
if (!subscription) { | ||
// We only want to start the subscription when the user starts iterating. | ||
subscription = this.subscribe({ | ||
next: (value) => { | ||
if (deferreds.length) { | ||
const [resolve] = deferreds.shift()!; | ||
resolve({ value, done: false }); | ||
} else { | ||
values.push(value); | ||
} | ||
}, | ||
error: handleError, | ||
complete: handleComplete, | ||
}); | ||
} | ||
|
||
// If we already have some values in our buffer, we'll return the next one. | ||
if (values.length) { | ||
return Promise.resolve({ value: values.shift()!, done: false }); | ||
benlesh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
// This was already completed, so we're just going to return a done result. | ||
if (completed) { | ||
return Promise.resolve({ value: undefined, done: true }); | ||
} | ||
|
||
// There was an error, so we're going to return an error result. | ||
if (hasError) { | ||
return Promise.reject(error); | ||
} | ||
|
||
// Otherwise, we need to make them wait for a value. | ||
return new Promise((resolve, reject) => { | ||
deferreds.push([resolve, reject]); | ||
}); | ||
}, | ||
throw: (err): Promise<IteratorResult<T>> => { | ||
subscription?.unsubscribe(); | ||
// NOTE: I did some research on this, and as of Feb 2023, Chrome doesn't seem to do | ||
// anything with pending promises returned from `next()` when `throw()` is called. | ||
// However, for consumption of observables, I don't want RxJS taking the heat for that | ||
// quirk/leak of the type. So we're going to reject all pending promises we've nexted out here. | ||
handleError(err); | ||
return Promise.reject(err); | ||
}, | ||
return: (): Promise<IteratorResult<T>> => { | ||
subscription?.unsubscribe(); | ||
// NOTE: I did some research on this, and as of Feb 2023, Chrome doesn't seem to do | ||
// anything with pending promises returned from `next()` when `throw()` is called. | ||
// However, for consumption of observables, I don't want RxJS taking the heat for that | ||
// quirk/leak of the type. So we're going to resolve all pending promises we've nexted out here. | ||
handleComplete(); | ||
return Promise.resolve({ value: undefined, done: true }); | ||
}, | ||
Comment on lines
+449
to
+466
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TIL |
||
[Symbol.asyncIterator]() { | ||
return this; | ||
}, | ||
}; | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.