[英]RxJava - upload files sequentially - emit next item, when onNext called
我有一种方法可以将多个文件同时上传到云存储。 它看起来像这样:
List<String> files = Arrays.asList("file0", "file1", "file2");
Observable.from(files)
.flatMap(file -> uploadFile(file)
.flatMap(done -> notifyFinished(file)))
.subscribe(this::onNext, this::onError, this::onCompleted);
private Observable<Boolean> uploadFile(String file) {
Timber.d("Uploading: " + file);
return Observable.just(true).delay(6, TimeUnit.SECONDS);
}
private Observable<Boolean> notifyFinished(String file) {
Timber.d("Notify finished: " + file);
return Observable.just(true).delay(3, TimeUnit.SECONDS);
}
这个输出是:
06-09 02:10:04.779 D: Uploading: file0
06-09 02:10:04.780 D: Uploading: file1
06-09 02:10:04.781 D: Uploading: file2
06-09 02:10:10.782 D: Notify finished: file1
06-09 02:10:10.782 D: Notify finished: file0
06-09 02:10:10.783 D: Notify finished: file2
06-09 02:10:13.784 D: onNext
06-09 02:10:13.786 D: onNext
06-09 02:10:13.786 D: onNext
06-09 02:10:13.787 D: onCompleted
我希望它按顺序工作,例如:
1) Uploading: file0
2) Notify finished: file0
3) onNext
4) Uploading: file1
5) Notify finished: file1
6) onNext
...
用Rx做这样的事情有可能吗?
编辑
用concatMap
替换第一个flatMap
concatMap
完成了这项工作。 我以为我知道这些运算符之间的区别,但这个例子只是表明我什么都不知道......现在输出是:
06-09 02:15:00.581 D: Uploading: file0
06-09 02:15:06.584 D: Notify finished: file0
06-09 02:15:09.586 D: onNext
06-09 02:15:09.587 D: Uploading: file1
06-09 02:15:15.590 D: Notify finished: file1
06-09 02:15:18.593 D: onNext
06-09 02:15:18.595 D: Uploading: file2
06-09 02:15:24.598 D: Notify finished: file2
06-09 02:15:27.599 D: onNext
06-09 02:15:27.601 D: onCompleted
如果你想要'有序'的连续顺序,只需使用concatMap()
而不是flatMap()
为每个文件创建一个observable并连接三个observable
@Test
public void testContact() {
Observable.concat(Observable.just(uploadFile(file1)),
Observable.just(uploadFile(file2)),
Observable.just(uploadFile(file3)))
.flatMap(file -> notifyFinished(file)))
.subscribe(this::onNext, this::onError, this::onCompleted);
}
您必须使方法notifyFinished返回observable文件而不是boolean。
你也可以使用merge或zip,你有更多组合observables的例子https://github.com/politrons/reactive/tree/master/src/test/java/rx/observables/combining
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.