[6a3a178] | 1 | import { Observable } from '../Observable';
|
---|
| 2 | import { AsyncSubject } from '../AsyncSubject';
|
---|
| 3 | import { multicast } from './multicast';
|
---|
| 4 | import { ConnectableObservable } from '../observable/ConnectableObservable';
|
---|
| 5 | import { UnaryFunction } from '../types';
|
---|
| 6 |
|
---|
| 7 | /**
|
---|
| 8 | * Returns a connectable observable sequence that shares a single subscription to the
|
---|
| 9 | * underlying sequence containing only the last notification.
|
---|
| 10 | *
|
---|
| 11 | * ![](publishLast.png)
|
---|
| 12 | *
|
---|
| 13 | * Similar to {@link publish}, but it waits until the source observable completes and stores
|
---|
| 14 | * the last emitted value.
|
---|
| 15 | * Similarly to {@link publishReplay} and {@link publishBehavior}, this keeps storing the last
|
---|
| 16 | * value even if it has no more subscribers. If subsequent subscriptions happen, they will
|
---|
| 17 | * immediately get that last stored value and complete.
|
---|
| 18 | *
|
---|
| 19 | * ## Example
|
---|
| 20 | *
|
---|
| 21 | * ```ts
|
---|
| 22 | * import { interval } from 'rxjs';
|
---|
| 23 | * import { publishLast, tap, take } from 'rxjs/operators';
|
---|
| 24 | *
|
---|
| 25 | * const connectable =
|
---|
| 26 | * interval(1000)
|
---|
| 27 | * .pipe(
|
---|
| 28 | * tap(x => console.log("side effect", x)),
|
---|
| 29 | * take(3),
|
---|
| 30 | * publishLast());
|
---|
| 31 | *
|
---|
| 32 | * connectable.subscribe(
|
---|
| 33 | * x => console.log( "Sub. A", x),
|
---|
| 34 | * err => console.log("Sub. A Error", err),
|
---|
| 35 | * () => console.log( "Sub. A Complete"));
|
---|
| 36 | *
|
---|
| 37 | * connectable.subscribe(
|
---|
| 38 | * x => console.log( "Sub. B", x),
|
---|
| 39 | * err => console.log("Sub. B Error", err),
|
---|
| 40 | * () => console.log( "Sub. B Complete"));
|
---|
| 41 | *
|
---|
| 42 | * connectable.connect();
|
---|
| 43 | *
|
---|
| 44 | * // Results:
|
---|
| 45 | * // "side effect 0"
|
---|
| 46 | * // "side effect 1"
|
---|
| 47 | * // "side effect 2"
|
---|
| 48 | * // "Sub. A 2"
|
---|
| 49 | * // "Sub. B 2"
|
---|
| 50 | * // "Sub. A Complete"
|
---|
| 51 | * // "Sub. B Complete"
|
---|
| 52 | * ```
|
---|
| 53 | *
|
---|
| 54 | * @see {@link ConnectableObservable}
|
---|
| 55 | * @see {@link publish}
|
---|
| 56 | * @see {@link publishReplay}
|
---|
| 57 | * @see {@link publishBehavior}
|
---|
| 58 | *
|
---|
| 59 | * @return {ConnectableObservable} An observable sequence that contains the elements of a
|
---|
| 60 | * sequence produced by multicasting the source sequence.
|
---|
| 61 | * @method publishLast
|
---|
| 62 | * @owner Observable
|
---|
| 63 | */
|
---|
| 64 |
|
---|
| 65 | export function publishLast<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>> {
|
---|
| 66 | return (source: Observable<T>) => multicast(new AsyncSubject<T>())(source);
|
---|
| 67 | }
|
---|