The sample operator emits the last item received on its source observable, either at fixed intervals or on receipt of items from another observable. The following figure shows the marble diagram of this operator when sampling is done by time:
The following figure shows the marble diagram of the sample operator when sampling is done via another observable:
The prototype of this operator is the following:
Observable.sample(self, interval=None, sampler=None, scheduler=None)
Here, the interval and sampler parameters are exclusive. The interval parameter specifies the sampling period in milliseconds. The sampler parameter is an observable that controls the sampling. Each time it emits an item, sampling of the source observable is performed. The scheduler parameter can be used to specify the scheduler to use. The default value uses the timeout scheduler.
Here is an example of this operator, with sampling controlled via a sampler observable:
numbers = Subject()
sampler = Subject()
numbers.sample(sampler=sampler).subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)
numbers.on_next(1)
numbers.on_next(2)
sampler.on_next(True)
numbers.on_next(3)
numbers.on_next(4)
numbers.on_next(5)
sampler.on_next(True)
This example gives the following result: