| 1 |
import { MonoTypeOperatorFunction, Observer } from '../types'; |
| 2 |
import { isFunction } from '../util/isFunction'; |
| 3 |
import { operate } from '../util/lift'; |
| 4 |
import { createOperatorSubscriber } from './OperatorSubscriber'; |
| 5 |
import { identity } from '../util/identity'; |
| 6 |
|
| 7 |
/** |
| 8 |
* An extension to the {@link Observer} interface used only by the {@link tap} operator. |
| 9 |
* |
| 10 |
* It provides a useful set of callbacks a user can register to do side-effects in |
| 11 |
* cases other than what the usual {@link Observer} callbacks are |
| 12 |
* ({@link guide/glossary-and-semantics#next next}, |
| 13 |
* {@link guide/glossary-and-semantics#error error} and/or |
| 14 |
* {@link guide/glossary-and-semantics#complete complete}). |
| 15 |
* |
| 16 |
* ## Example |
| 17 |
* |
| 18 |
* ```ts |
| 19 |
* import { fromEvent, switchMap, tap, interval, take } from 'rxjs'; |
| 20 |
* |
| 21 |
* const source$ = fromEvent(document, 'click'); |
| 22 |
* const result$ = source$.pipe( |
| 23 |
* switchMap((_, i) => i % 2 === 0 |
| 24 |
* ? fromEvent(document, 'mousemove').pipe( |
| 25 |
* tap({ |
| 26 |
* subscribe: () => console.log('Subscribed to the mouse move events after click #' + i), |
| 27 |
* unsubscribe: () => console.log('Mouse move events #' + i + ' unsubscribed'), |
| 28 |
* finalize: () => console.log('Mouse move events #' + i + ' finalized') |
| 29 |
* }) |
| 30 |
* ) |
| 31 |
* : interval(1_000).pipe( |
| 32 |
* take(5), |
| 33 |
* tap({ |
| 34 |
* subscribe: () => console.log('Subscribed to the 1-second interval events after click #' + i), |
| 35 |
* unsubscribe: () => console.log('1-second interval events #' + i + ' unsubscribed'), |
| 36 |
* finalize: () => console.log('1-second interval events #' + i + ' finalized') |
| 37 |
* }) |
| 38 |
* ) |
| 39 |
* ) |
| 40 |
* ); |
| 41 |
* |
| 42 |
* const subscription = result$.subscribe({ |
| 43 |
* next: console.log |
| 44 |
* }); |
| 45 |
* |
| 46 |
* setTimeout(() => { |
| 47 |
* console.log('Unsubscribe after 60 seconds'); |
| 48 |
* subscription.unsubscribe(); |
| 49 |
* }, 60_000); |
| 50 |
* ``` |
| 51 |
*/ |
| 52 |
export interface TapObserver<T> extends Observer<T> { |
| 53 |
/** |
| 54 |
* The callback that `tap` operator invokes at the moment when the source Observable |
| 55 |
* gets subscribed to. |
| 56 |
*/ |
| 57 |
subscribe: () => void; |
| 58 |
/** |
| 59 |
* The callback that `tap` operator invokes when an explicit |
| 60 |
* {@link guide/glossary-and-semantics#unsubscription unsubscribe} happens. It won't get invoked on |
| 61 |
* `error` or `complete` events. |
| 62 |
*/ |
| 63 |
unsubscribe: () => void; |
| 64 |
/** |
| 65 |
* The callback that `tap` operator invokes when any kind of |
| 66 |
* {@link guide/glossary-and-semantics#finalization finalization} happens - either when |
| 67 |
* the source Observable `error`s or `complete`s or when it gets explicitly unsubscribed |
| 68 |
* by the user. There is no difference in using this callback or the {@link finalize} |
| 69 |
* operator, but if you're already using `tap` operator, you can use this callback |
| 70 |
* instead. You'd get the same result in either case. |
| 71 |
*/ |
| 72 |
finalize: () => void; |
| 73 |
} |
| 74 |
export function tap<T>(observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void)): MonoTypeOperatorFunction<T>; |
| 75 |
/** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */ |
| 76 |
export function tap<T>( |
| 77 |
next?: ((value: T) => void) | null, |
| 78 |
error?: ((error: any) => void) | null, |
| 79 |
complete?: (() => void) | null |
| 80 |
): MonoTypeOperatorFunction<T>; |
| 81 |
|
| 82 |
/** |
| 83 |
* Used to perform side-effects for notifications from the source observable |
| 84 |
* |
| 85 |
* <span class="informal">Used when you want to affect outside state with a notification without altering the notification</span> |
| 86 |
* |
| 87 |
*  |
| 88 |
* |
| 89 |
* Tap is designed to allow the developer a designated place to perform side effects. While you _could_ perform side-effects |
| 90 |
* inside of a `map` or a `mergeMap`, that would make their mapping functions impure, which isn't always a big deal, but will |
| 91 |
* make it so you can't do things like memoize those functions. The `tap` operator is designed solely for such side-effects to |
| 92 |
* help you remove side-effects from other operations. |
| 93 |
* |
| 94 |
* For any notification, next, error, or complete, `tap` will call the appropriate callback you have provided to it, via a function |
| 95 |
* reference, or a partial observer, then pass that notification down the stream. |
| 96 |
* |
| 97 |
* The observable returned by `tap` is an exact mirror of the source, with one exception: Any error that occurs -- synchronously -- in a handler |
| 98 |
* provided to `tap` will be emitted as an error from the returned observable. |
| 99 |
* |
| 100 |
* > Be careful! You can mutate objects as they pass through the `tap` operator's handlers. |
| 101 |
* |
| 102 |
* The most common use of `tap` is actually for debugging. You can place a `tap(console.log)` anywhere |
| 103 |
* in your observable `pipe`, log out the notifications as they are emitted by the source returned by the previous |
| 104 |
* operation. |
| 105 |
* |
| 106 |
* ## Examples |
| 107 |
* |
| 108 |
* Check a random number before it is handled. Below is an observable that will use a random number between 0 and 1, |
| 109 |
* and emit `'big'` or `'small'` depending on the size of that number. But we wanted to log what the original number |
| 110 |
* was, so we have added a `tap(console.log)`. |
| 111 |
* |
| 112 |
* ```ts |
| 113 |
* import { of, tap, map } from 'rxjs'; |
| 114 |
* |
| 115 |
* of(Math.random()).pipe( |
| 116 |
* tap(console.log), |
| 117 |
* map(n => n > 0.5 ? 'big' : 'small') |
| 118 |
* ).subscribe(console.log); |
| 119 |
* ``` |
| 120 |
* |
| 121 |
* Using `tap` to analyze a value and force an error. Below is an observable where in our system we only |
| 122 |
* want to emit numbers 3 or less we get from another source. We can force our observable to error |
| 123 |
* using `tap`. |
| 124 |
* |
| 125 |
* ```ts |
| 126 |
* import { of, tap } from 'rxjs'; |
| 127 |
* |
| 128 |
* const source = of(1, 2, 3, 4, 5); |
| 129 |
* |
| 130 |
* source.pipe( |
| 131 |
* tap(n => { |
| 132 |
* if (n > 3) { |
| 133 |
* throw new TypeError(`Value ${ n } is greater than 3`); |
| 134 |
* } |
| 135 |
* }) |
| 136 |
* ) |
| 137 |
* .subscribe({ next: console.log, error: err => console.log(err.message) }); |
| 138 |
* ``` |
| 139 |
* |
| 140 |
* We want to know when an observable completes before moving on to the next observable. The system |
| 141 |
* below will emit a random series of `'X'` characters from 3 different observables in sequence. The |
| 142 |
* only way we know when one observable completes and moves to the next one, in this case, is because |
| 143 |
* we have added a `tap` with the side effect of logging to console. |
| 144 |
* |
| 145 |
* ```ts |
| 146 |
* import { of, concatMap, interval, take, map, tap } from 'rxjs'; |
| 147 |
* |
| 148 |
* of(1, 2, 3).pipe( |
| 149 |
* concatMap(n => interval(1000).pipe( |
| 150 |
* take(Math.round(Math.random() * 10)), |
| 151 |
* map(() => 'X'), |
| 152 |
* tap({ complete: () => console.log(`Done with ${ n }`) }) |
| 153 |
* )) |
| 154 |
* ) |
| 155 |
* .subscribe(console.log); |
| 156 |
* ``` |
| 157 |
* |
| 158 |
* @see {@link finalize} |
| 159 |
* @see {@link TapObserver} |
| 160 |
* |
| 161 |
* @param observerOrNext A next handler or partial observer |
| 162 |
* @param error An error handler |
| 163 |
* @param complete A completion handler |
| 164 |
* @return A function that returns an Observable identical to the source, but |
| 165 |
* runs the specified Observer or callback(s) for each item. |
| 166 |
*/ |
| 167 |
export function tap<T>( |
| 168 |
observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void) | null, |
| 169 |
error?: ((e: any) => void) | null, |
| 170 |
complete?: (() => void) | null |
| 171 |
): MonoTypeOperatorFunction<T> { |
| 172 |
// We have to check to see not only if next is a function, |
| 173 |
// but if error or complete were passed. This is because someone |
| 174 |
// could technically call tap like `tap(null, fn)` or `tap(null, null, fn)`. |
| 175 |
const tapObserver = |
| 176 |
isFunction(observerOrNext) || error || complete |
| 177 |
? // tslint:disable-next-line: no-object-literal-type-assertion |
| 178 |
({ next: observerOrNext as Exclude<typeof observerOrNext, Partial<TapObserver<T>>>, error, complete } as Partial<TapObserver<T>>) |
| 179 |
: observerOrNext; |
| 180 |
|
| 181 |
return tapObserver |
| 182 |
? operate((source, subscriber) => { |
| 183 |
tapObserver.subscribe?.(); |
| 184 |
let isUnsub = true; |
| 185 |
source.subscribe( |
| 186 |
createOperatorSubscriber( |
| 187 |
subscriber, |
| 188 |
(value) => { |
| 189 |
tapObserver.next?.(value); |
| 190 |
subscriber.next(value); |
| 191 |
}, |
| 192 |
() => { |
| 193 |
isUnsub = false; |
| 194 |
tapObserver.complete?.(); |
| 195 |
subscriber.complete(); |
| 196 |
}, |
| 197 |
(err) => { |
| 198 |
isUnsub = false; |
| 199 |
tapObserver.error?.(err); |
| 200 |
subscriber.error(err); |
| 201 |
}, |
| 202 |
() => { |
| 203 |
if (isUnsub) { |
| 204 |
tapObserver.unsubscribe?.(); |
| 205 |
} |
| 206 |
tapObserver.finalize?.(); |
| 207 |
} |
| 208 |
) |
| 209 |
); |
| 210 |
}) |
| 211 |
: // Tap was called with no valid tap observer or handler |
| 212 |
// (e.g. `tap(null, null, null)` or `tap(null)` or `tap()`) |
| 213 |
// so we're going to just mirror the source. |
| 214 |
identity; |
| 215 |
} |