The time_interval operator

The time_interval operator measures the time that has elapsed between two emissions of items. The following figure shows the marble diagram for this operator:

Figure 9.21: The time_interval operator

The prototype of this operator is the following:

Observable.time_interval(self, scheduler=None)

Here, scheduler is the scheduler to use to measure the interval. If no scheduler is provided, then the timeout scheduler is used. The time_interval operator emits items of type TimeInterval. They contain two properties:

  • value, which contains the value of the source item
  • interval, which contains a datetime.timedelta object

Here is an example of this operator:

numbers = Subject()

numbers.time_interval().subscribe(
on_next = lambda i: print("on_next {}: {}".format(i.value, i.interval)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)

numbers.on_next(1)
numbers.on_next(2)
time.sleep(0.1)
numbers.on_next(3)
time.sleep(0.2)
numbers.on_next(4)

The first two objects are emitted immediately. The third item is emitted after a delay of 100 milliseconds, and the fourth item after another delay of 200 milliseconds.

This example gives the following result:

on_next 1: 0:00:00.000155
on_next 2: 0:00:00.000305
on_next 3: 0:00:00.100798
on_next 4: 0:00:00.204477

This is the expected result: items 1 and 2 are received almost at the same time, item 3 is received 100 milliseconds after item 2, and item 4 is received 200 milliseconds after item 3.

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

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