| 1 |
import { OperatorFunction, TimestampProvider, Timestamp } from '../types'; |
| 2 |
import { dateTimestampProvider } from '../scheduler/dateTimestampProvider'; |
| 3 |
import { map } from './map'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Attaches a timestamp to each item emitted by an observable indicating when it was emitted |
| 7 |
* |
| 8 |
* The `timestamp` operator maps the *source* observable stream to an object of type |
| 9 |
* `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value |
| 10 |
* and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By |
| 11 |
* default, it uses the `asyncScheduler` which simply returns `Date.now()` (milliseconds since 1970/01/01 |
| 12 |
* 00:00:00:000) and therefore is of type `number`. |
| 13 |
* |
| 14 |
*  |
| 15 |
* |
| 16 |
* ## Example |
| 17 |
* |
| 18 |
* In this example there is a timestamp attached to the document's click events |
| 19 |
* |
| 20 |
* ```ts |
| 21 |
* import { fromEvent, timestamp } from 'rxjs'; |
| 22 |
* |
| 23 |
* const clickWithTimestamp = fromEvent(document, 'click').pipe( |
| 24 |
* timestamp() |
| 25 |
* ); |
| 26 |
* |
| 27 |
* // Emits data of type { value: PointerEvent, timestamp: number } |
| 28 |
* clickWithTimestamp.subscribe(data => { |
| 29 |
* console.log(data); |
| 30 |
* }); |
| 31 |
* ``` |
| 32 |
* |
| 33 |
* @param timestampProvider An object with a `now()` method used to get the current timestamp. |
| 34 |
* @return A function that returns an Observable that attaches a timestamp to |
| 35 |
* each item emitted by the source Observable indicating when it was emitted. |
| 36 |
*/ |
| 37 |
export function timestamp<T>(timestampProvider: TimestampProvider = dateTimestampProvider): OperatorFunction<T, Timestamp<T>> { |
| 38 |
return map((value: T) => ({ value, timestamp: timestampProvider.now() })); |
| 39 |
} |