【问题标题】:RxJava - upload files sequentially - emit next item, when onNext calledRxJava - 按顺序上传文件 - 在调用 onNext 时发出下一个项目
【发布时间】:2016-06-08 22:27:45
【问题描述】:

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

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 就可以了。我以为我知道这些运算符之间的区别,但这个例子只是表明我什么都不知道......现在输出是:

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

【问题讨论】:

  • 你想做什么?看起来它已经按顺序工作了。你看到的是什么顺序?
  • 示例很糟糕,请检查我的编辑。

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


【解决方案1】:

如果您想要“有序”连续,只需使用concatMap() 而不是flatMap()

【讨论】:

    【解决方案2】:

    为每个文件创建一个可观察对象并连接三个可观察对象

    @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 返回可观察文件而不是布尔值。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多