重复运算符
repeat
运算符允许从源 Observable
重复整个序列。
Observable.just(1, 2, 3)
.repeat()
.subscribe(
next -> System.out.println("next: " + next),
error -> System.out.println("error: " + error),
() -> System.out.println("complete")
);
以上示例的输出
next: 1
next: 2
next: 3
next: 1
next: 2
next: 3
这个序列重复无数次,永远不会完成。
要重复序列有限次数,只需将整数作为参数传递给 repeat
运算符。
Observable.just(1, 2, 3)
// Repeat three times and complete
.repeat(3)
.subscribe(
next -> System.out.println("next: " + next),
error -> System.out.println("error: " + error),
() -> System.out.println("complete")
);
这个例子打印
next: 1
next: 2
next: 3
next: 1
next: 2
next: 3
next: 1
next: 2
next: 3
complete
了解 repeat
运算符在源 Observable
序列完成时重新订阅源 Observable
非常重要。让我们用 Observable.create
重写上面的例子。
Observable.<Integer>create(subscriber -> {
//Same as Observable.just(1, 2, 3) but with output message
System.out.println("Subscribed");
subscriber.onNext(1);
subscriber.onNext(2);
subscriber.onNext(3);
subscriber.onCompleted();
})
.repeat(3)
.subscribe(
next -> System.out.println("next: " + next),
error -> System.out.println("error: " + error),
() -> System.out.println("complete")
);
这个例子打印
Subscribed
next: 1
next: 2
next: 3
Subscribed
next: 1
next: 2
next: 3
Subscribed
next: 1
next: 2
next: 3
complete
使用运算符链接时,重要的是要知道 repeat
运算符重复整个序列而不是前面的运算符。
Observable.<Integer>create(subscriber -> {
System.out.println("Subscribed");
subscriber.onNext(1);
subscriber.onNext(2);
subscriber.onNext(3);
subscriber.onCompleted();
})
.map(value -> value * 2) //First chain operator
.map(value -> "modified " + value) //Second chain operator
.repeat(3)
.subscribe(
next -> System.out.println("next: " + next),
error -> System.out.println("error: " + error),
() -> System.out.println("complete")
);
这个例子打印
Subscribed
next: modified 2
next: modified 4
next: modified 6
Subscribed
next: modified 2
next: modified 4
next: modified 6
Subscribed
next: modified 2
next: modified 4
next: modified 6
complete
这个例子表明 repeat
运算符重复整个序列重新订阅 Observable
而不是重复最后的 map
运算符,并且 repeat
运算符序列中的哪个位置无关紧要。
这个序列
Observable.<Integer>create(subscriber -> {
//...
})
.map(value -> value * 2) //First chain operator
.map(value -> "modified " + value) //Second chain operator
.repeat(3)
.subscribe(
/*....*/
);
等于这个序列
Observable.<Integer>create(subscriber -> {
//...
})
.repeat(3)
.map(value -> value * 2) //First chain operator
.map(value -> "modified " + value) //Second chain operator
.subscribe(
/*....*/
);