##// END OF EJS Templates
Movin the observable implementation to the class
cin -
r153:8ae7abbb3114 default
parent child
Show More
@@ -0,0 +1,169
1 import { id as mid } from "module";
2 import { AccumulatorFn, FusedProducer, Observable, Observer, OperatorFn } from "./interfaces";
3 import { TraceSource } from "@implab/core-amd/log/TraceSource";
4 import { scan } from "dojo/parser";
5 import { filter } from "dojo/query";
6
7 const trace = TraceSource.get(mid);
8
9 const noop = () => { };
10
11 const errorFallback = (e: unknown) => trace.error("Unhandled observable error: {0}", e);
12
13 const sink = <T>(consumer: Observer<T>) => {
14 // eslint-disable-next-line @typescript-eslint/unbound-method
15 const { next, error, complete } = consumer;
16 return {
17 next: next ? next.bind(consumer) : noop,
18 error: error ? error.bind(consumer) : errorFallback, // report unhandled errors
19 complete: complete ? complete.bind(consumer) : noop
20 };
21 };
22
23 const
24
25 export class ObservableImpl<T> implements Observable<T> {
26
27 private readonly _producer: FusedProducer<T>;
28
29 constructor(producer: FusedProducer<T>) {
30 this._producer = producer;
31 }
32
33 subscribe(consumer: Observer<T> = {}) {
34 return {
35 unsubscribe: this._producer(sink(consumer)) ?? noop
36 }
37 }
38
39 map<T2>(mapper: (value: T) => T2) {
40 return new ObservableImpl<T2>(({ next, ...rest }) =>
41 this._producer({
42 next: next !== noop ? (v: T) => next(mapper(v)) : noop,
43 ...rest
44 }));
45 }
46
47 tap({ next: tapNext, complete: tapComplete, error: tapError }: Observer<T>) {
48 return new ObservableImpl<T>(({ next, complete, error }) =>
49 this._producer({
50 next: tapNext ? (v => (tapNext(v), next(v))) : next,
51 complete: tapComplete ? (() => (tapComplete(), complete())) : complete,
52 error: tapError ? (e => (tapError(e), error(e))) : error
53 }));
54 }
55
56 filter: (predicate) => _observe(({ next, ...rest }) =>
57 producer({
58 next: next !== noop ? (v: T) => predicate(v) ? next(v) : void (0) : noop,
59 ...rest
60 })
61 ),
62
63 until: predicate => _observe(({ next, complete, ...rest }) =>
64 producer({
65 next: v => predicate(v) ? complete() : next(v),
66 complete,
67 ...rest
68 })
69 ),
70
71 while: predicate => _observe(({ next, complete, ...rest }) =>
72 producer({
73 next: v => predicate(v) ? next(v) : complete(),
74 complete,
75 ...rest
76 })
77 ),
78
79 scan: <A>(...args: [AccumulatorFn<T, A>, A] | [AccumulatorFn<T, T>]) => _observe<T | A>(({ next, ...rest }) => {
80 if (args.length === 1) {
81 const [accumulator] = args;
82 let _acc: T;
83 let index = 0;
84 return producer({
85 next: next !== noop ? (v: T) => next(index++ === 0 ? _acc = v : _acc = accumulator(_acc, v)) : noop,
86 ...rest
87 });
88 } else {
89 const [accumulator, initial] = args;
90 let _acc = initial;
91 return producer({
92 next: next !== noop ? (v: T) => next(_acc = accumulator(_acc, v)) : noop,
93 ...rest
94 });
95 }
96 }),
97
98 reduce: <A>(...args: [AccumulatorFn<T, A>, A] | [AccumulatorFn<T, T>]) => _observe<T | A>(({ next, complete, error }) => {
99 if (args.length === 1) {
100 const [accumulator] = args;
101 let _acc: T;
102 let index = 0;
103 return producer({
104 next: next !== noop ? (v: T) => {
105 _acc = index++ === 0 ? v : accumulator(_acc, v);
106 } : noop,
107 complete: () => {
108 if (index === 0) {
109 error(new Error("The sequence can't be empty"));
110 } else {
111 next(_acc);
112 complete();
113 }
114 },
115 error
116 });
117 } else {
118 const [accumulator, initial] = args;
119 let _acc = initial;
120 return producer({
121 next: next !== noop ? (v: T) => {
122 _acc = accumulator(_acc, v);
123 } : noop,
124 complete: () => {
125 next(_acc);
126 complete();
127 },
128 error
129 });
130 }
131 }),
132
133 cat: (...seq) => _observe(({ next, complete: final, ...rest }) => {
134 let cleanup: () => void;
135 const len = seq.length;
136 const complete = (i: number) => i < len ?
137 () => {
138 const subscription = seq[i].subscribe({ next, complete: complete(i + 1), ...rest });
139 cleanup = subscription.unsubscribe.bind(subscription);
140 } : final;
141
142 cleanup = producer({ next, complete: complete(0), ...rest }) ?? noop;
143
144 return () => cleanup();
145 }),
146
147 pipe: <U>(op: OperatorFn<T, U>) => op(_observe(producer)),
148
149 next: collect(
150 producer,
151 ({ next, complete, error }) => ({
152 next: v => (next(v), complete()),
153 complete: () => error(new Error("The sequence is empty")),
154 error
155 })
156 ),
157
158 collect: collect(
159 producer,
160 ({ next, complete, error }) => {
161 const data: T[] = [];
162 return {
163 next: v => data.push(v),
164 complete: () => (next(data), complete()),
165 error
166 };
167 }
168 )
169 } No newline at end of file
@@ -0,0 +1,153
1 import { ICancellation } from "@implab/core-amd/interfaces";
2
3 /**
4 * The interface for the consumer of an observable sequence
5 */
6 export interface Observer<T> {
7 /**
8 * Called for the next element in the sequence
9 */
10 next?(value: T): void;
11
12 /**
13 * Called once when the error occurs in the sequence.
14 */
15 error?(e: unknown): void;
16
17 /**
18 * Called once at the end of the sequence.
19 */
20 complete?(): void;
21 }
22
23 /**
24 * The group of functions to feed an observable. These methods are provided to
25 * the producer to generate a stream of events.
26 */
27 export type Sink<T> = {
28 /**
29 * Call to send the next element in the sequence
30 */
31 next: (value: T) => void;
32
33 /**
34 * Call to notify about the error occurred in the sequence.
35 */
36 error: (e: unknown) => void;
37
38 /**
39 * Call to signal the end of the sequence.
40 */
41 complete: () => void;
42
43 /**
44 * Checks whether the sink is accepting new elements. It's safe to
45 * send elements to the closed sink.
46 */
47 isClosed: () => boolean;
48 };
49
50 export type Producer<T> = (sink: Sink<T>) => (void | (() => void));
51
52 export type FusedSink<T> = Omit<Sink<T>, "isClosed">;
53
54 export type FusedProducer<T> = (sink: FusedSink<T>) => (void | (() => void));
55
56 export interface Unsubscribable {
57 unsubscribe(): void;
58 }
59
60 export interface Subscribable<T> {
61 /** Subscribes a consumer to events. If a consumer isn't specified
62 * this method activates the producer to achieve side affects if any.
63 */
64 subscribe(consumer?: Observer<T>): Unsubscribable;
65 }
66
67 export type AccumulatorFn<T, A> = (acc: A, value: T) => A;
68
69 export type OperatorFn<T, U> = (source: Observable<T>) => Observable<U>;
70
71 /** The observable source of items. */
72 export interface Observable<T> extends Subscribable<T> {
73 /** Transforms elements of the sequence with the specified mapper
74 *
75 * @param mapper The mapper used to transform the values
76 */
77 map<T2>(mapper: (value: T) => T2): Observable<T2>;
78
79 /** Injects the specified observer into the each producer to consumer chain.
80 * The method is used to add side effect to the events processing.
81 *
82 * @param observer The consumer for the events
83 */
84 tap(observer: Observer<T>): Observable<T>;
85
86 /** Filters elements of the sequence. The resulting sequence will
87 * contain only elements which match the specified predicate.
88 *
89 * @param predicate The filter predicate.
90 */
91 filter(predicate: (value: T) => boolean): Observable<T>;
92
93 /** Completes the sequence once the condition is met.
94 * @param predicate The condition which should be met to complete the sequence
95 */
96 until(predicate: (value: T) => boolean): Observable<T>;
97
98 /** Keeps the sequence running while elements satisfy the condition.
99 *
100 * @param predicate The condition which should be met to continue.
101 */
102 while(predicate: (value: T) => boolean): Observable<T>;
103
104 /** Applies accumulator to each value in the sequence and
105 * emits the accumulated value for each source element
106 *
107 * @param accumulator
108 * @param initial
109 */
110 scan<A>(accumulator: AccumulatorFn<T, A>, initial: A): Observable<A>;
111 scan(accumulator: AccumulatorFn<T, T>): Observable<T>;
112
113 /** Applies accumulator to each value in the sequence and
114 * emits the accumulated value at the end of the sequence
115 *
116 * @param accumulator
117 * @param initial
118 */
119 reduce<A>(accumulator: AccumulatorFn<T, A>, initial: A): Observable<A>;
120 reduce(accumulator: AccumulatorFn<T, T>): Observable<T>;
121
122 /** Concatenates the specified sequences with this observable
123 *
124 * @param seq sequences to concatenate with the current observable
125 *
126 * The concatenation doesn't accumulate values from the specified sequences,
127 * The result of the concatenation is the new observable which will switch
128 * to the next observable after the previous one completes. Values emitted
129 * before the next observable being active are lost.
130 */
131 cat(...seq: Subscribable<T>[]): Observable<T>;
132
133
134 /** Pipes the specified operator to produce the new observable
135 * @param op The operator consumes this observable and produces a new one
136 *
137 * The operator is a higher order function which takes a source observable
138 * and returns a producer for the new observable.
139 *
140 * This function can be used to create a complex mapping between source and
141 * resulting observables. The operator may have a state (or a side effect)
142 * and can be connected to multiple observables.
143 */
144 pipe<U>(op: OperatorFn<T, U>): Observable<U>;
145
146 /** Waits for the next event to occur and returns a promise for the next value
147 * @param ct Cancellation token
148 */
149 next(ct?: ICancellation): Promise<T>;
150
151 /** Collects items of the sequence to the array. */
152 collect(ct?: ICancellation): Promise<T[]>;
153 } No newline at end of file
@@ -1,67 +1,10
1 import { id as mid} from "module";
1 import { id as mid} from "module";
2 import { Cancellation } from "@implab/core-amd/Cancellation";
2 import { Cancellation } from "@implab/core-amd/Cancellation";
3 import { ICancellation } from "@implab/core-amd/interfaces";
4 import { TraceSource } from "@implab/core-amd/log/TraceSource";
3 import { TraceSource } from "@implab/core-amd/log/TraceSource";
5 import { isPromise } from "@implab/core-amd/safe";
4 import { isPromise } from "@implab/core-amd/safe";
6
5 import { Unsubscribable, Observer, Producer, FusedSink, FusedProducer, AccumulatorFn, Observable, OperatorFn, Subscribable } from "./observable/interfaces";
7 const trace = TraceSource.get(mid);
8
9 /**
10 * The interface for the consumer of an observable sequence
11 */
12 export interface Observer<T> {
13 /**
14 * Called for the next element in the sequence
15 */
16 next?(value: T): void;
17
18 /**
19 * Called once when the error occurs in the sequence.
20 */
21 error?(e: unknown): void;
22
23 /**
24 * Called once at the end of the sequence.
25 */
26 complete?(): void;
27 }
28
6
29 /**
30 * The group of functions to feed an observable. These methods are provided to
31 * the producer to generate a stream of events.
32 */
33 export type Sink<T> = {
34 /**
35 * Call to send the next element in the sequence
36 */
37 next: (value: T) => void;
38
7
39 /**
40 * Call to notify about the error occurred in the sequence.
41 */
42 error: (e: unknown) => void;
43
44 /**
45 * Call to signal the end of the sequence.
46 */
47 complete: () => void;
48
49 /**
50 * Checks whether the sink is accepting new elements. It's safe to
51 * send elements to the closed sink.
52 */
53 isClosed: () => boolean;
54 };
55
56 export type Producer<T> = (sink: Sink<T>) => (void | (() => void));
57
58 type FusedSink<T> = Omit<Sink<T>, "isClosed">;
59
60 type FusedProducer<T> = (sink: FusedSink<T>) => (void | (() => void));
61
62 export interface Unsubscribable {
63 unsubscribe(): void;
64 }
65
8
66 export const isUnsubscribable = (v: unknown): v is Unsubscribable =>
9 export const isUnsubscribable = (v: unknown): v is Unsubscribable =>
67 v !== null && v !== undefined && typeof (v as Unsubscribable).unsubscribe === "function";
10 v !== null && v !== undefined && typeof (v as Unsubscribable).unsubscribe === "function";
@@ -69,104 +12,11 export const isUnsubscribable = (v: unkn
69 export const isSubscribable = <T = unknown>(v: unknown): v is Subscribable<T> =>
12 export const isSubscribable = <T = unknown>(v: unknown): v is Subscribable<T> =>
70 v !== null && v !== undefined && typeof (v as Subscribable<unknown>).subscribe === "function";
13 v !== null && v !== undefined && typeof (v as Subscribable<unknown>).subscribe === "function";
71
14
72 export interface Subscribable<T> {
73 /** Subscribes a consumer to events. If a consumer isn't specified
74 * this method activates the producer to achieve side affects if any.
75 */
76 subscribe(consumer?: Observer<T>): Unsubscribable;
77 }
78
15
79 export type AccumulatorFn<T, A> = (acc: A, value: T) => A;
80
81 export type OperatorFn<T, U> = (source: Observable<T>) => Observable<U>;
82
83 /** The observable source of items. */
84 export interface Observable<T> extends Subscribable<T> {
85 /** Transforms elements of the sequence with the specified mapper
86 *
87 * @param mapper The mapper used to transform the values
88 */
89 map<T2>(mapper: (value: T) => T2): Observable<T2>;
90
91 /** Injects the specified observer into the each producer to consumer chain.
92 * The method is used to add side effect to the events processing.
93 *
94 * @param observer The consumer for the events
95 */
96 tap(observer: Observer<T>): Observable<T>;
97
98 /** Filters elements of the sequence. The resulting sequence will
99 * contain only elements which match the specified predicate.
100 *
101 * @param predicate The filter predicate.
102 */
103 filter(predicate: (value: T) => boolean): Observable<T>;
104
105 /** Completes the sequence once the condition is met.
106 * @param predicate The condition which should be met to complete the sequence
107 */
108 until(predicate: (value: T) => boolean): Observable<T>;
109
110 /** Keeps the sequence running while elements satisfy the condition.
111 *
112 * @param predicate The condition which should be met to continue.
113 */
114 while(predicate: (value: T) => boolean): Observable<T>;
115
116 /** Applies accumulator to each value in the sequence and
117 * emits the accumulated value for each source element
118 *
119 * @param accumulator
120 * @param initial
121 */
122 scan<A>(accumulator: AccumulatorFn<T, A>, initial: A): Observable<A>;
123 scan(accumulator: AccumulatorFn<T, T>): Observable<T>;
124
125 /** Applies accumulator to each value in the sequence and
126 * emits the accumulated value at the end of the sequence
127 *
128 * @param accumulator
129 * @param initial
130 */
131 reduce<A>(accumulator: AccumulatorFn<T, A>, initial: A): Observable<A>;
132 reduce(accumulator: AccumulatorFn<T, T>): Observable<T>;
133
134 /** Concatenates the specified sequences with this observable
135 *
136 * @param seq sequences to concatenate with the current observable
137 *
138 * The concatenation doesn't accumulate values from the specified sequences,
139 * The result of the concatenation is the new observable which will switch
140 * to the next observable after the previous one completes. Values emitted
141 * before the next observable being active are lost.
142 */
143 cat(...seq: Subscribable<T>[]): Observable<T>;
144
145
146 /** Pipes the specified operator to produce the new observable
147 * @param op The operator consumes this observable and produces a new one
148 *
149 * The operator is a higher order function which takes a source observable
150 * and returns a producer for the new observable.
151 *
152 * This function can be used to create a complex mapping between source and
153 * resulting observables. The operator may have a state (or a side effect)
154 * and can be connected to multiple observables.
155 */
156 pipe<U>(op: OperatorFn<T, U>): Observable<U>;
157
158 /** Waits for the next event to occur and returns a promise for the next value
159 * @param ct Cancellation token
160 */
161 next(ct?: ICancellation): Promise<T>;
162
163 /** Collects items of the sequence to the array. */
164 collect(ct?: ICancellation): Promise<T[]>;
165 }
166
16
167 const noop = () => { };
17 const noop = () => { };
168
18
169 const errorFallback = (e: unknown) => trace.error("Unhandled observable error: {0}", e);
19
170
20
171 const sink = <T>(consumer: Observer<T>) => {
21 const sink = <T>(consumer: Observer<T>) => {
172 // eslint-disable-next-line @typescript-eslint/unbound-method
22 // eslint-disable-next-line @typescript-eslint/unbound-method
@@ -30,6 +30,7
30 },
30 },
31 "../djx/build/npm/package": {
31 "../djx/build/npm/package": {
32 "name": "@implab/djx",
32 "name": "@implab/djx",
33 "version": "1.10.0",
33 "dev": true,
34 "dev": true,
34 "license": "BSD-2-Clause",
35 "license": "BSD-2-Clause",
35 "peerDependencies": {
36 "peerDependencies": {
General Comments 0
You need to be logged in to leave comments. Login now