RxJava - 按顺序上传文件 - 当onNext调用时,发出下一个项目

时间:2016-06-08 22:27:46

标签: java android multithreading rx-java reactive-programming

我有一种方法可以将多个文件同时上传到云端存储。它看起来像这样:

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做这样的事情?

修改

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

2 个答案:

答案 0 :(得分:5)

如果您想要“有序”的连续顺序,只需使用concatMap()代替flatMap()

答案 1 :(得分:1)

为每个文件创建一个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。

您也可以使用合并或zip,这里有更多组合observable的例子https://github.com/politrons/reactive/tree/master/src/test/java/rx/observables/combining