eff1725e2d95f94cbff7eff5c230fd99f567d2086984aad1f970ba48bce0701b0e384056a59d0d880ab23ee159e6dcdae0c71635b03fe2c231dfa3642a7ff8 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { Observable } from '../Observable';
  2. import { Operator } from '../Operator';
  3. import { Subscriber } from '../Subscriber';
  4. import { EmptyError } from '../util/EmptyError';
  5. import { OperatorFunction } from '../../internal/types';
  6. import { filter } from './filter';
  7. import { takeLast } from './takeLast';
  8. import { throwIfEmpty } from './throwIfEmpty';
  9. import { defaultIfEmpty } from './defaultIfEmpty';
  10. import { identity } from '../util/identity';
  11. /* tslint:disable:max-line-length */
  12. export function last<T, D = T>(
  13. predicate?: null,
  14. defaultValue?: D
  15. ): OperatorFunction<T, T | D>;
  16. export function last<T, S extends T>(
  17. predicate: (value: T, index: number, source: Observable<T>) => value is S,
  18. defaultValue?: S
  19. ): OperatorFunction<T, S>;
  20. export function last<T, D = T>(
  21. predicate: (value: T, index: number, source: Observable<T>) => boolean,
  22. defaultValue?: D
  23. ): OperatorFunction<T, T | D>;
  24. /* tslint:enable:max-line-length */
  25. /**
  26. * Returns an Observable that emits only the last item emitted by the source Observable.
  27. * It optionally takes a predicate function as a parameter, in which case, rather than emitting
  28. * the last item from the source Observable, the resulting Observable will emit the last item
  29. * from the source Observable that satisfies the predicate.
  30. *
  31. * ![](last.png)
  32. *
  33. * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
  34. * callback if the Observable completes before any `next` notification was sent.
  35. * @param {function} [predicate] - The condition any source emitted item has to satisfy.
  36. * @param {any} [defaultValue] - An optional default value to provide if last
  37. * predicate isn't met or no values were emitted.
  38. * @return {Observable} An Observable that emits only the last item satisfying the given condition
  39. * from the source, or an NoSuchElementException if no such items are emitted.
  40. * @throws - Throws if no items that match the predicate are emitted by the source Observable.
  41. */
  42. export function last<T, D>(
  43. predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,
  44. defaultValue?: D
  45. ): OperatorFunction<T, T | D> {
  46. const hasDefaultValue = arguments.length >= 2;
  47. return (source: Observable<T>) => source.pipe(
  48. predicate ? filter((v, i) => predicate(v, i, source)) : identity,
  49. takeLast(1),
  50. hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
  51. );
  52. }