The RxJS audit and auditTime operators silence a stream temporarily. That means values are ignored until a second Observable emits (audit) or during a certain duration (auditTime). Importantly, after this waiting time the most recent value is emitted.
Silence values with RxJS audit
Audit expects an Observable as argument that determines the silence duration. The first arriving value actives this duration selector Observable. In below example we basically output the numbers from 1 to 20 by emitting a number every 100ms. Because we added an interval(500) as audit duration selector a value is emitted at most every 500ms. This results in the output 5, 10, 15, 20.
interval(100).pipe(
map(v => v + 1),
take(20),
audit(ev => interval(500)),
).subscribe({
next: console.log
})
// 5
// 10
// 15
// 20
The example with interval(500) for audit does not make that much sense (auditTime would be a better fit). The audit operator should be used in cases where the rate really depends on another Observable.
Compared to buffer the audit operator drops some values. It’s a rate limiter only letting through the most recent value every time the duration selector emits.
RxJS auditTime rate limits based on time
We can achieve the “a value at most every 500ms” more easily by using auditTime instead of audit:
interval(100).pipe(
map(v => v + 1),
take(20),
auditTime(500),
).subscribe({
next: console.log,
})
// 5
// 10
// 15
// 20
Exercise for the RxJS audit operator 💪
Implement a function that emits words but only if the enter key is pressed. You can take this code as a starting point index_starter.html.
The result should look like below. Every time you press enter a word is marked!
As always the code examples can be found on GitHub.