Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mapTo.ts 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { Operator } from '../Operator';
  2. import { Subscriber } from '../Subscriber';
  3. import { Observable } from '../Observable';
  4. import { OperatorFunction } from '../types';
  5. /**
  6. * Emits the given constant value on the output Observable every time the source
  7. * Observable emits a value.
  8. *
  9. * <span class="informal">Like {@link map}, but it maps every source value to
  10. * the same output value every time.</span>
  11. *
  12. * ![](mapTo.png)
  13. *
  14. * Takes a constant `value` as argument, and emits that whenever the source
  15. * Observable emits a value. In other words, ignores the actual source value,
  16. * and simply uses the emission moment to know when to emit the given `value`.
  17. *
  18. * ## Example
  19. * Map every click to the string 'Hi'
  20. * ```ts
  21. * import { fromEvent } from 'rxjs';
  22. * import { mapTo } from 'rxjs/operators';
  23. *
  24. * const clicks = fromEvent(document, 'click');
  25. * const greetings = clicks.pipe(mapTo('Hi'));
  26. * greetings.subscribe(x => console.log(x));
  27. * ```
  28. *
  29. * @see {@link map}
  30. *
  31. * @param {any} value The value to map each source value to.
  32. * @return {Observable} An Observable that emits the given `value` every time
  33. * the source Observable emits something.
  34. * @method mapTo
  35. * @owner Observable
  36. */
  37. export function mapTo<T, R>(value: R): OperatorFunction<T, R> {
  38. return (source: Observable<T>) => source.lift(new MapToOperator(value));
  39. }
  40. class MapToOperator<T, R> implements Operator<T, R> {
  41. value: R;
  42. constructor(value: R) {
  43. this.value = value;
  44. }
  45. call(subscriber: Subscriber<R>, source: any): any {
  46. return source.subscribe(new MapToSubscriber(subscriber, this.value));
  47. }
  48. }
  49. /**
  50. * We need this JSDoc comment for affecting ESDoc.
  51. * @ignore
  52. * @extends {Ignored}
  53. */
  54. class MapToSubscriber<T, R> extends Subscriber<T> {
  55. value: R;
  56. constructor(destination: Subscriber<R>, value: R) {
  57. super(destination);
  58. this.value = value;
  59. }
  60. protected _next(x: T) {
  61. this.destination.next(this.value);
  62. }
  63. }