Home » RxJS sample() Filtering Operator

RxJS sample() Filtering Operator

by Online Tutorials Library

RxJS sample() Filtering Operator

RxJS sample() operator is a filtering operator that emits the most recent emitted value from the source Observable within a periodic time interval whenever another Observable, the notifier, emits. The output depends upon the argument passed to it.

The RxJS sample() operator periodically checks the source observable and emits whichever item it finds the most recently emitted since the previous sampling.

Syntax:

Following is the syntax of the RxJS sample() operator:

Or

Parameter Explanation

notifier: The notifier argument is an observable which will decide the output to be picked. It is used for sampling the source observable.

Return value

The RxJS sample() operator’s return value is an observable that emits the results of sampling the values emitted by the source observable whenever the notifier observable emits value or completes.

Let us see some examples of the RxJS sample() operator to understand it clearly.

Example 1 (Sample source after every 2 seconds)

Output:

After executing the above example, you will see the following result:

RxJS sample() Filtering Operator

Example 2 (Sample source when interval emits)

Output:

After executing the above example, you will see the following result:

RxJS sample() Filtering Operator

Example 3 (Distinguish between drag and click)

Output:

After executing the above example, you will see the following result:

RxJS sample() Filtering Operator

In the above example, you can see that when you drag your mouse on the RxJS playground while clicking on the left button, it shows the true result otherwise, false.


Next TopicRxJS Operators

You may also like