gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:19 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于java - RxJava - 按顺序上传文件 - 在调用 onNext 时发出下一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com