| 1 |
/* @prettier */ |
| 2 |
import { SchedulerLike } from '../types'; |
| 3 |
import { Observable } from '../Observable'; |
| 4 |
import { bindCallbackInternals } from './bindCallbackInternals'; |
| 5 |
|
| 6 |
export function bindCallback( |
| 7 |
callbackFunc: (...args: any[]) => void, |
| 8 |
resultSelector: (...args: any[]) => any, |
| 9 |
scheduler?: SchedulerLike |
| 10 |
): (...args: any[]) => Observable<any>; |
| 11 |
|
| 12 |
// args is the arguments array and we push the callback on the rest tuple since the rest parameter must be last (only item) in a parameter list |
| 13 |
export function bindCallback<A extends readonly unknown[], R extends readonly unknown[]>( |
| 14 |
callbackFunc: (...args: [...A, (...res: R) => void]) => void, |
| 15 |
schedulerLike?: SchedulerLike |
| 16 |
): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>; |
| 17 |
|
| 18 |
/** |
| 19 |
* Converts a callback API to a function that returns an Observable. |
| 20 |
* |
| 21 |
* <span class="informal">Give it a function `f` of type `f(x, callback)` and |
| 22 |
* it will return a function `g` that when called as `g(x)` will output an |
| 23 |
* Observable.</span> |
| 24 |
* |
| 25 |
* `bindCallback` is not an operator because its input and output are not |
| 26 |
* Observables. The input is a function `func` with some parameters. The |
| 27 |
* last parameter must be a callback function that `func` calls when it is |
| 28 |
* done. |
| 29 |
* |
| 30 |
* The output of `bindCallback` is a function that takes the same parameters |
| 31 |
* as `func`, except the last one (the callback). When the output function |
| 32 |
* is called with arguments it will return an Observable. If function `func` |
| 33 |
* calls its callback with one argument, the Observable will emit that value. |
| 34 |
* If on the other hand the callback is called with multiple values the resulting |
| 35 |
* Observable will emit an array with said values as arguments. |
| 36 |
* |
| 37 |
* It is **very important** to remember that input function `func` is not called |
| 38 |
* when the output function is, but rather when the Observable returned by the output |
| 39 |
* function is subscribed. This means if `func` makes an AJAX request, that request |
| 40 |
* will be made every time someone subscribes to the resulting Observable, but not before. |
| 41 |
* |
| 42 |
* The last optional parameter - `scheduler` - can be used to control when the call |
| 43 |
* to `func` happens after someone subscribes to Observable, as well as when results |
| 44 |
* passed to callback will be emitted. By default, the subscription to an Observable calls `func` |
| 45 |
* synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`, |
| 46 |
* just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler |
| 47 |
* and call `subscribe` on the output Observable, all function calls that are currently executing |
| 48 |
* will end before `func` is invoked. |
| 49 |
* |
| 50 |
* By default, results passed to the callback are emitted immediately after `func` invokes the callback. |
| 51 |
* In particular, if the callback is called synchronously, then the subscription of the resulting Observable |
| 52 |
* will call the `next` function synchronously as well. If you want to defer that call, |
| 53 |
* you may use {@link asyncScheduler} just as before. This means that by using `Scheduler.async` you can |
| 54 |
* ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo. |
| 55 |
* |
| 56 |
* Note that the Observable created by the output function will always emit a single value |
| 57 |
* and then complete immediately. If `func` calls the callback multiple times, values from subsequent |
| 58 |
* calls will not appear in the stream. If you need to listen for multiple calls, |
| 59 |
* you probably want to use {@link fromEvent} or {@link fromEventPattern} instead. |
| 60 |
* |
| 61 |
* If `func` depends on some context (`this` property) and is not already bound, the context of `func` |
| 62 |
* will be the context that the output function has at call time. In particular, if `func` |
| 63 |
* is called as a method of some object and if `func` is not already bound, in order to preserve the context |
| 64 |
* it is recommended that the context of the output function is set to that object as well. |
| 65 |
* |
| 66 |
* If the input function calls its callback in the "node style" (i.e. first argument to callback is |
| 67 |
* optional error parameter signaling whether the call failed or not), {@link bindNodeCallback} |
| 68 |
* provides convenient error handling and probably is a better choice. |
| 69 |
* `bindCallback` will treat such functions the same as any other and error parameters |
| 70 |
* (whether passed or not) will always be interpreted as regular callback argument. |
| 71 |
* |
| 72 |
* ## Examples |
| 73 |
* |
| 74 |
* Convert jQuery's getJSON to an Observable API |
| 75 |
* |
| 76 |
* ```ts |
| 77 |
* import { bindCallback } from 'rxjs'; |
| 78 |
* import * as jQuery from 'jquery'; |
| 79 |
* |
| 80 |
* // Suppose we have jQuery.getJSON('/my/url', callback) |
| 81 |
* const getJSONAsObservable = bindCallback(jQuery.getJSON); |
| 82 |
* const result = getJSONAsObservable('/my/url'); |
| 83 |
* result.subscribe(x => console.log(x), e => console.error(e)); |
| 84 |
* ``` |
| 85 |
* |
| 86 |
* Receive an array of arguments passed to a callback |
| 87 |
* |
| 88 |
* ```ts |
| 89 |
* import { bindCallback } from 'rxjs'; |
| 90 |
* |
| 91 |
* const someFunction = (n, s, cb) => { |
| 92 |
* cb(n, s, { someProperty: 'someValue' }); |
| 93 |
* }; |
| 94 |
* |
| 95 |
* const boundSomeFunction = bindCallback(someFunction); |
| 96 |
* boundSomeFunction(5, 'some string').subscribe((values) => { |
| 97 |
* console.log(values); // [5, 'some string', {someProperty: 'someValue'}] |
| 98 |
* }); |
| 99 |
* ``` |
| 100 |
* |
| 101 |
* Compare behaviour with and without `asyncScheduler` |
| 102 |
* |
| 103 |
* ```ts |
| 104 |
* import { bindCallback, asyncScheduler } from 'rxjs'; |
| 105 |
* |
| 106 |
* function iCallMyCallbackSynchronously(cb) { |
| 107 |
* cb(); |
| 108 |
* } |
| 109 |
* |
| 110 |
* const boundSyncFn = bindCallback(iCallMyCallbackSynchronously); |
| 111 |
* const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, asyncScheduler); |
| 112 |
* |
| 113 |
* boundSyncFn().subscribe(() => console.log('I was sync!')); |
| 114 |
* boundAsyncFn().subscribe(() => console.log('I was async!')); |
| 115 |
* console.log('This happened...'); |
| 116 |
* |
| 117 |
* // Logs: |
| 118 |
* // I was sync! |
| 119 |
* // This happened... |
| 120 |
* // I was async! |
| 121 |
* ``` |
| 122 |
* |
| 123 |
* Use `bindCallback` on an object method |
| 124 |
* |
| 125 |
* ```ts |
| 126 |
* import { bindCallback } from 'rxjs'; |
| 127 |
* |
| 128 |
* const boundMethod = bindCallback(someObject.methodWithCallback); |
| 129 |
* boundMethod |
| 130 |
* .call(someObject) // make sure methodWithCallback has access to someObject |
| 131 |
* .subscribe(subscriber); |
| 132 |
* ``` |
| 133 |
* |
| 134 |
* @see {@link bindNodeCallback} |
| 135 |
* @see {@link from} |
| 136 |
* |
| 137 |
* @param callbackFunc A function with a callback as the last parameter. |
| 138 |
* @param resultSelector A mapping function used to transform callback events. |
| 139 |
* @param scheduler The scheduler on which to schedule the callbacks. |
| 140 |
* @return A function which returns the Observable that delivers the same |
| 141 |
* values the callback would deliver. |
| 142 |
*/ |
| 143 |
export function bindCallback( |
| 144 |
callbackFunc: (...args: [...any[], (...res: any) => void]) => void, |
| 145 |
resultSelector?: ((...args: any[]) => any) | SchedulerLike, |
| 146 |
scheduler?: SchedulerLike |
| 147 |
): (...args: any[]) => Observable<unknown> { |
| 148 |
return bindCallbackInternals(false, callbackFunc, resultSelector, scheduler); |
| 149 |
} |