官术网_书友最值得收藏!

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
主站蜘蛛池模板: 阳山县| 邵武市| 天长市| 且末县| 连州市| 屯昌县| 仁布县| 丘北县| 侯马市| 五台县| 乌恰县| 清徐县| 五寨县| 淳化县| 麻栗坡县| 丰镇市| 绿春县| 孟州市| 衡南县| 井研县| 莱西市| 德兴市| 湖南省| 贺兰县| 轮台县| 司法| 阿拉尔市| 祁连县| 扶沟县| 蒙自县| 罗源县| 西城区| 麻阳| 台中县| 康保县| 福州市| 三门县| 修文县| 临潭县| 韩城市| 武鸣县|