The range operator

The range operator creates an observable that emits integer items within a range of values. Its marble diagram is shown in the following figure:

Figure 4.3: The range operator

Its prototype is as follows:

Observable.range(start, count, scheduler=None)

The start parameter is the initial value of the sequence of numbers that is emitted on the observable. The count parameter indicates the number of items to send. So, creating a sequence from 1 to 4 can be done as follows:

numbers = Observable.range(1, 4)
numbers.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The preceding sample code prints the values from 1 to 4 before completing, as follows:

item: 1
item: 2
item: 3
item: 4
completed

Like many other operators, this one is available in most, if not all, implementations of ReactiveX. However, in Python, this operator is almost syntactic sugar for the from_ operator, combined with the built-in Python range function. The same result from the preceding code can be obtained as follows:

numbers = Observable.from_(range(1, 5))
numbers.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

Using the Python range function instead of the range operator makes it possible to use other steps than 1. The following example generates a sequence of odd numbers, from 1 to 9:

numbers = Observable.from_(range(1, 10, 2))
numbers.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The preceding code will provide the following output:

item: 1
item: 3
item: 5
item: 7
item: 9
completed
..................Content has been hidden....................

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