[6a3a178] | 1 |
|
---|
| 2 | import { async } from '../scheduler/async';
|
---|
| 3 | import { OperatorFunction, SchedulerLike, Timestamp as TimestampInterface } from '../types';
|
---|
| 4 | import { map } from './map';
|
---|
| 5 |
|
---|
| 6 | /**
|
---|
| 7 | * Attaches a timestamp to each item emitted by an observable indicating when it was emitted
|
---|
| 8 | *
|
---|
| 9 | * The `timestamp` operator maps the *source* observable stream to an object of type
|
---|
| 10 | * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value
|
---|
| 11 | * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By
|
---|
| 12 | * default it uses the *async* scheduler which simply returns `Date.now()` (milliseconds since 1970/01/01
|
---|
| 13 | * 00:00:00:000) and therefore is of type `number`.
|
---|
| 14 | *
|
---|
| 15 | * ![](timestamp.png)
|
---|
| 16 | *
|
---|
| 17 | * ## Example
|
---|
| 18 | *
|
---|
| 19 | * In this example there is a timestamp attached to the documents click event.
|
---|
| 20 | *
|
---|
| 21 | * ```ts
|
---|
| 22 | * import { fromEvent } from 'rxjs';
|
---|
| 23 | * import { timestamp } from 'rxjs/operators';
|
---|
| 24 | *
|
---|
| 25 | * const clickWithTimestamp = fromEvent(document, 'click').pipe(
|
---|
| 26 | * timestamp()
|
---|
| 27 | * );
|
---|
| 28 | *
|
---|
| 29 | * // Emits data of type {value: MouseEvent, timestamp: number}
|
---|
| 30 | * clickWithTimestamp.subscribe(data => {
|
---|
| 31 | * console.log(data);
|
---|
| 32 | * });
|
---|
| 33 | * ```
|
---|
| 34 | *
|
---|
| 35 | * @param scheduler
|
---|
| 36 | * @return {Observable<Timestamp<any>>|WebSocketSubject<T>|Observable<T>}
|
---|
| 37 | * @method timestamp
|
---|
| 38 | * @owner Observable
|
---|
| 39 | */
|
---|
| 40 | export function timestamp<T>(scheduler: SchedulerLike = async): OperatorFunction<T, Timestamp<T>> {
|
---|
| 41 | return map((value: T) => new Timestamp(value, scheduler.now()));
|
---|
| 42 | // return (source: Observable<T>) => source.lift(new TimestampOperator(scheduler));
|
---|
| 43 | }
|
---|
| 44 |
|
---|
| 45 | export class Timestamp<T> implements TimestampInterface<T> {
|
---|
| 46 | constructor(public value: T, public timestamp: number) {
|
---|
| 47 | }
|
---|
| 48 | }
|
---|