Debian Codegraph @

node/rxjs/src/internal/observable/fromEventPattern.ts

raw
1 import { Observable } from '../Observable';
2 import { isFunction } from '../util/isFunction';
3 import { NodeEventHandler } from './fromEvent';
4 import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
5
6 /* tslint:disable:max-line-length */
7 export function fromEventPattern<T>(
8 addHandler: (handler: NodeEventHandler) => any,
9 removeHandler?: (handler: NodeEventHandler, signal?: any) => void
10 ): Observable<T>;
11 export function fromEventPattern<T>(
12 addHandler: (handler: NodeEventHandler) => any,
13 removeHandler?: (handler: NodeEventHandler, signal?: any) => void,
14 resultSelector?: (...args: any[]) => T
15 ): Observable<T>;
16 /* tslint:enable:max-line-length */
17
18 /**
19 * Creates an Observable from an arbitrary API for registering event handlers.
20 *
21 * <span class="informal">When that method for adding event handler was something {@link fromEvent}
22 * was not prepared for.</span>
23 *
24 * ![](fromEventPattern.png)
25 *
26 * `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions
27 * for events. It is similar to {@link fromEvent}, but far
28 * more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by
29 * `fromEventPattern` (although in slightly more verbose way).
30 *
31 * This operator accepts as a first argument an `addHandler` function, which will be injected with
32 * handler parameter. That handler is actually an event handler function that you now can pass
33 * to API expecting it. `addHandler` will be called whenever Observable
34 * returned by the operator is subscribed, so registering handler in API will not
35 * necessarily happen when `fromEventPattern` is called.
36 *
37 * After registration, every time an event that we listen to happens,
38 * Observable returned by `fromEventPattern` will emit value that event handler
39 * function was called with. Note that if event handler was called with more
40 * than one argument, second and following arguments will not appear in the Observable.
41 *
42 * If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`
43 * another function - `removeHandler` - as a second parameter. It will be injected
44 * with the same handler function as before, which now you can use to unregister
45 * it from the API. `removeHandler` will be called when consumer of resulting Observable
46 * unsubscribes from it.
47 *
48 * In some APIs unregistering is actually handled differently. Method registering an event handler
49 * returns some kind of token, which is later used to identify which function should
50 * be unregistered or it itself has method that unregisters event handler.
51 * If that is the case with your API, make sure token returned
52 * by registering method is returned by `addHandler`. Then it will be passed
53 * as a second argument to `removeHandler`, where you will be able to use it.
54 *
55 * If you need access to all event handler parameters (not only the first one),
56 * or you need to transform them in any way, you can call `fromEventPattern` with optional
57 * third parameter - project function which will accept all arguments passed to
58 * event handler when it is called. Whatever is returned from project function will appear on
59 * resulting stream instead of usual event handlers first argument. This means
60 * that default project can be thought of as function that takes its first parameter
61 * and ignores the rest.
62 *
63 * ## Examples
64 *
65 * Emits clicks happening on the DOM document
66 *
67 * ```ts
68 * import { fromEventPattern } from 'rxjs';
69 *
70 * function addClickHandler(handler) {
71 * document.addEventListener('click', handler);
72 * }
73 *
74 * function removeClickHandler(handler) {
75 * document.removeEventListener('click', handler);
76 * }
77 *
78 * const clicks = fromEventPattern(
79 * addClickHandler,
80 * removeClickHandler
81 * );
82 * clicks.subscribe(x => console.log(x));
83 *
84 * // Whenever you click anywhere in the browser, DOM MouseEvent
85 * // object will be logged.
86 * ```
87 *
88 * Use with API that returns cancellation token
89 *
90 * ```ts
91 * import { fromEventPattern } from 'rxjs';
92 *
93 * const token = someAPI.registerEventHandler(function() {});
94 * someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts
95 * // not handler itself, but special token.
96 *
97 * const someAPIObservable = fromEventPattern(
98 * function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...
99 * function(handler, token) { someAPI.unregisterEventHandler(token); } // ...to then use it here.
100 * );
101 * ```
102 *
103 * Use with project function
104 *
105 * ```ts
106 * import { fromEventPattern } from 'rxjs';
107 *
108 * someAPI.registerEventHandler((eventType, eventMessage) => {
109 * console.log(eventType, eventMessage); // Logs 'EVENT_TYPE' 'EVENT_MESSAGE' to console.
110 * });
111 *
112 * const someAPIObservable = fromEventPattern(
113 * handler => someAPI.registerEventHandler(handler),
114 * handler => someAPI.unregisterEventHandler(handler)
115 * (eventType, eventMessage) => eventType + ' --- ' + eventMessage // without that function only 'EVENT_TYPE'
116 * ); // would be emitted by the Observable
117 *
118 * someAPIObservable.subscribe(value => console.log(value));
119 *
120 * // Logs:
121 * // 'EVENT_TYPE --- EVENT_MESSAGE'
122 * ```
123 *
124 * @see {@link fromEvent}
125 * @see {@link bindCallback}
126 * @see {@link bindNodeCallback}
127 *
128 * @param addHandler A function that takes a `handler` function as argument and attaches it
129 * somehow to the actual source of events.
130 * @param removeHandler A function that takes a `handler` function as an argument and removes
131 * it from the event source. If `addHandler` returns some kind of token, `removeHandler` function
132 * will have it as a second parameter.
133 * @param resultSelector A function to transform results. It takes the arguments from the event
134 * handler and should return a single value.
135 * @return Observable which, when an event happens, emits first parameter passed to registered
136 * event handler. Alternatively it emits whatever project function returns at that moment.
137 */
138 export function fromEventPattern<T>(
139 addHandler: (handler: NodeEventHandler) => any,
140 removeHandler?: (handler: NodeEventHandler, signal?: any) => void,
141 resultSelector?: (...args: any[]) => T
142 ): Observable<T | T[]> {
143 if (resultSelector) {
144 return fromEventPattern<T>(addHandler, removeHandler).pipe(mapOneOrManyArgs(resultSelector));
145 }
146
147 return new Observable<T | T[]>((subscriber) => {
148 const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);
149 const retValue = addHandler(handler);
150 return isFunction(removeHandler) ? () => removeHandler(handler, retValue) : undefined;
151 });
152 }