| 1 |
import { MonoTypeOperatorFunction } from '../types'; |
| 2 |
import { operate } from '../util/lift'; |
| 3 |
|
| 4 |
/** |
| 5 |
* Returns an Observable that mirrors the source Observable, but will call a specified function when |
| 6 |
* the source terminates on complete or error. |
| 7 |
* The specified function will also be called when the subscriber explicitly unsubscribes. |
| 8 |
* |
| 9 |
* ## Examples |
| 10 |
* |
| 11 |
* Execute callback function when the observable completes |
| 12 |
* |
| 13 |
* ```ts |
| 14 |
* import { interval, take, finalize } from 'rxjs'; |
| 15 |
* |
| 16 |
* // emit value in sequence every 1 second |
| 17 |
* const source = interval(1000); |
| 18 |
* const example = source.pipe( |
| 19 |
* take(5), //take only the first 5 values |
| 20 |
* finalize(() => console.log('Sequence complete')) // Execute when the observable completes |
| 21 |
* ); |
| 22 |
* const subscribe = example.subscribe(val => console.log(val)); |
| 23 |
* |
| 24 |
* // results: |
| 25 |
* // 0 |
| 26 |
* // 1 |
| 27 |
* // 2 |
| 28 |
* // 3 |
| 29 |
* // 4 |
| 30 |
* // 'Sequence complete' |
| 31 |
* ``` |
| 32 |
* |
| 33 |
* Execute callback function when the subscriber explicitly unsubscribes |
| 34 |
* |
| 35 |
* ```ts |
| 36 |
* import { interval, finalize, tap, noop, timer } from 'rxjs'; |
| 37 |
* |
| 38 |
* const source = interval(100).pipe( |
| 39 |
* finalize(() => console.log('[finalize] Called')), |
| 40 |
* tap({ |
| 41 |
* next: () => console.log('[next] Called'), |
| 42 |
* error: () => console.log('[error] Not called'), |
| 43 |
* complete: () => console.log('[tap complete] Not called') |
| 44 |
* }) |
| 45 |
* ); |
| 46 |
* |
| 47 |
* const sub = source.subscribe({ |
| 48 |
* next: x => console.log(x), |
| 49 |
* error: noop, |
| 50 |
* complete: () => console.log('[complete] Not called') |
| 51 |
* }); |
| 52 |
* |
| 53 |
* timer(150).subscribe(() => sub.unsubscribe()); |
| 54 |
* |
| 55 |
* // results: |
| 56 |
* // '[next] Called' |
| 57 |
* // 0 |
| 58 |
* // '[finalize] Called' |
| 59 |
* ``` |
| 60 |
* |
| 61 |
* @param callback Function to be called when source terminates. |
| 62 |
* @return A function that returns an Observable that mirrors the source, but |
| 63 |
* will call the specified function on termination. |
| 64 |
*/ |
| 65 |
export function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> { |
| 66 |
return operate((source, subscriber) => { |
| 67 |
// TODO: This try/finally was only added for `useDeprecatedSynchronousErrorHandling`. |
| 68 |
// REMOVE THIS WHEN THAT HOT GARBAGE IS REMOVED IN V8. |
| 69 |
try { |
| 70 |
source.subscribe(subscriber); |
| 71 |
} finally { |
| 72 |
subscriber.add(callback); |
| 73 |
} |
| 74 |
}); |
| 75 |
} |