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: