In Angular's RxJS library, the audit
and auditTime
operators are used to control the rate of emissions from an observable, particularly for scenarios like managing user input or throttling network requests.
audit
Operator
The audit
operator lets you ignore emitted values for a specified duration and then emits the most recent value after that duration. It uses a function that returns an observable to determine when to allow another emission.
Usage
import { fromEvent, interval } from 'rxjs';
import { audit } from 'rxjs/operators';
// Example observable (mouse clicks)
const clicks$ = fromEvent(document, 'click');
// Apply the audit operator with a 1-second interval
const result$ = clicks$.pipe(audit(() => interval(1000)));
// Subscribe to the result
result$.subscribe(event => console.log('Clicked:', event));
In this example, after a click is registered, the audit
operator will ignore subsequent clicks for 1 second and then emit the most recent click event.
auditTime
Operator
The auditTime
operator is a simpler version of audit
that uses a fixed duration (in milliseconds) to determine when to allow another emission. It waits for the specified duration, then emits the most recent value, and then ignores subsequent values until the duration has passed again.
Usage
import { fromEvent } from 'rxjs';
import { auditTime } from 'rxjs/operators';
// Example observable (mouse clicks)
const clicks$ = fromEvent(document, 'click');
// Apply the auditTime operator with a 1-second duration
const result$ = clicks$.pipe(auditTime(1000));
// Subscribe to the result
result$.subscribe(event => console.log('Clicked:', event));
In this example, after a click is registered, the auditTime
operator will ignore subsequent clicks for 1 second and then emit the most recent click event after each 1-second period.
Key Differences
-
Emission Control
- audit: Uses a function that returns an observable to determine the audit duration dynamically.
- auditTime: Uses a fixed duration specified in milliseconds.
-
Use Cases
- audit: Suitable when the audit duration needs to be based on more complex logic or dynamic conditions.
- auditTime: Simpler and suitable for fixed-rate throttling scenarios.
Both operators are useful for managing high-frequency events and can help in scenarios where you need to limit the number of emitted values over time, such as handling button clicks or other frequent user interactions in Angular applications