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

The repeat operator

The repeat operator allows for repeating the emission of an item or a sequence. The marble diagram of the repeat operator is shown in the following figure:

Figure 4.4: The repeat operator

This operator has two prototypes, as follows:

Observable.repeat(value=None, repeat_count=None, scheduler=None)
Observable.repeat(self, repeat_count=None)

The first implementation is a static class method. It can be used to create an observable that repeats value items for repeat_count times. If the value is not set, items with a None value are emitted. The second implementation is a method that repeats its source observable for repeat_count times. In both methods, the repeat_count argument is optional. When repeat_count is not set, the repetition is infinite. If the repeat_count is less than one, then no items are emitted.

The first variant of the implementation can be used in the following way:

ones = Observable.repeat(1, 5)
ones.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: 1
item: 1
item: 1
item: 1
completed

The second variant is used in a chain of operators, like in the following simple example:

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

First, the numbers observable is created. Upon subscription, it emits the sequence 1, 2, 3. This sequence is then repeated three times. This provides the following result:

item: 1
item: 2
item: 3
item: 1
item: 2
item: 3
item: 1
item: 2
item: 3
completed
In this case, the whole sequence is repeated, and not each item of the source observable. Repeating each item of an observable can be done by combining the static variant of the repeat operator with the flat_map operator. The flat_map operator will be discussed in Chapter 5,   Concurrency and Parallelism in RxPY.
主站蜘蛛池模板: 平果县| 旺苍县| 景德镇市| 获嘉县| 东丽区| 花垣县| 宁海县| 南溪县| 饶阳县| 潜江市| 若羌县| 庆元县| 葫芦岛市| 军事| 禹州市| 木里| 苏尼特右旗| 兴隆县| 将乐县| 淮南市| 庆元县| 木兰县| 德清县| 朝阳市| 延寿县| 靖州| 中卫市| 丘北县| 芦山县| 高要市| 醴陵市| 拜泉县| 安多县| 台南县| 扶绥县| 全椒县| 清水县| 清丰县| 迭部县| 铅山县| 栾城县|