All you need to know about audit operator in RxJS
The audit operator ignores the values emitted from the source observable for a duration as specified by another observable and when this duration is over, it emits the latest value from the source observable. All the previous values emitted by the source observable previous to the latest value, are ignored. One thing to observe here is that the parameter which dictates the duration of ignoring the source values must be an observable itself.
Signature
audit(durationSelector: Observable): MonoTypeOperatorFunction
durationSelector: It is a function that receives the time duration from the source observable.
MonoTypeOperatorFunction: It is an observable that performs rate-limiting of emissions from the source.
A simple demonstration of the audit operator can be shown as follows.
const timer = interval( 1000 ).pipe(take( 20 )); // (1)const result = timer.pipe(audit(ev => interval( 5000 ))); // (2)result.subscribe(val => console.log(val)); // (3)
Let’s follow the above code snippet step by step.
In step1, we created a new observable called times through the interval operator that emits continuous values after a given time interval, 1000ms here. Then we pass this observable value to the pipe operator and apply that to the take operator. The take operator executes only the first 20 values emitted from the source observable i.e. the interval operator here. So in a nutshell we can say that the constant value timer essentially emits 20 values starting from 0.
In step2, we pass the timer to a pipe again, this time through the audit operator and assign this to a new constant called result. The audit operator takes another observable as input to get the duration value and in our case it is again the interval operator which emits after every 5000ms.
In the last step, as with all our observables, we subscribe to the result and print the values.Quite straight forward, right.
In the output we get the following result.
// 5// 11// 17
This is all about the basics of the audit operator.