热的Observable发射物品。我想将这些项目上传到服务器。 有两个注意事项:
Uploads succeed:
1 - 2 - 3 - 4 - 5
------------------
u(1,2,3) - u(4,5)
First upload fails:
1 - 2 - 3 - 4 - 5
------------------
u(1,2,3) - u(1,2,3,4,5)
我可以使用buffer
运算符来处理第一个,但不知道如何满足第二个要求。
答案 0 :(得分:2)
这是我将故障存储在队列中的想法
public class StackOverflow {
public static void main(String[] args) {
// store any failures that may have occurred
LinkedBlockingQueue<String> failures = new LinkedBlockingQueue<>();
toUpload()
// buffer however you want
.buffer(5)
// here is the interesting part
.flatMap(strings -> {
// add any previous failures
List<String> prevFailures = new ArrayList<>();
failures.drainTo(prevFailures);
strings.addAll(prevFailures);
return Flowable.just(strings);
})
.flatMapCompletable(strings -> {
// upload the data
return upload(strings).doOnError(throwable -> {
// if its an upload failure:
failures.addAll(strings);
});
}).subscribe();
}
// whatever your source flowable is
private static Flowable<String> toUpload() {
return Flowable.fromIterable(Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i"));
}
// some upload operation
private static Completable upload(List<String> strings) {
return Completable.complete();
}
}
这里的一些极端情况是,如果最后一个可流动的缓冲组失败,则不会重试。可以通过retryWhen
运算符来实现,但基本思路与使用队列相同