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