Debian Codegraph @

node/rxjs/src/internal/scheduled/scheduleIterable.ts

raw
1 import { Observable } from '../Observable';
2 import { SchedulerLike } from '../types';
3 import { iterator as Symbol_iterator } from '../symbol/iterator';
4 import { isFunction } from '../util/isFunction';
5 import { executeSchedule } from '../util/executeSchedule';
6
7 /**
8 * Used in {@link scheduled} to create an observable from an Iterable.
9 * @param input The iterable to create an observable from
10 * @param scheduler The scheduler to use
11 */
12 export function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {
13 return new Observable<T>((subscriber) => {
14 let iterator: Iterator<T, T>;
15
16 // Schedule the initial creation of the iterator from
17 // the iterable. This is so the code in the iterable is
18 // not called until the scheduled job fires.
19 executeSchedule(subscriber, scheduler, () => {
20 // Create the iterator.
21 iterator = (input as any)[Symbol_iterator]();
22
23 executeSchedule(
24 subscriber,
25 scheduler,
26 () => {
27 let value: T;
28 let done: boolean | undefined;
29 try {
30 // Pull the value out of the iterator
31 ({ value, done } = iterator.next());
32 } catch (err) {
33 // We got an error while pulling from the iterator
34 subscriber.error(err);
35 return;
36 }
37
38 if (done) {
39 // If it is "done" we just complete. This mimics the
40 // behavior of JavaScript's `for..of` consumption of
41 // iterables, which will not emit the value from an iterator
42 // result of `{ done: true: value: 'here' }`.
43 subscriber.complete();
44 } else {
45 // The iterable is not done, emit the value.
46 subscriber.next(value);
47 }
48 },
49 0,
50 true
51 );
52 });
53
54 // During finalization, if we see this iterator has a `return` method,
55 // then we know it is a Generator, and not just an Iterator. So we call
56 // the `return()` function. This will ensure that any `finally { }` blocks
57 // inside of the generator we can hit will be hit properly.
58 return () => isFunction(iterator?.return) && iterator.return();
59 });
60 }