The sample operator

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:

Figure 9.9: The sample operator with time-based sampling

The following figure shows the marble diagram of the sample operator when sampling is done via another observable:

Figure 9.10: The sample operator with sampling being based on an 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:

on_next 2
on_next 5

Here, two items are received, corresponding to the last value emitted by the numbers observable each time the sampler observable emitted an item.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.29.22