如何在 RxSwift 中顺序和非并行循环遍历数组?

How do I sequentially and nonparallel loop through an array in RxSwift?

我有一个需要发送到服务器的对象列表,我想一个接一个地发送(不是并行)。在所有对象都已发送并且没有错误之后,我想 运行 额外的 Observables 做不同的事情。

let objects = [1, 2, 3]

let _ = Observable.from(objects).flatMap { object -> Observable<Void> in
    return Observable.create { observer in
        print("Starting request \(object)")
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { // one request takes ~2sec
            print("Request \(object) finished")
            observer.onNext(Void())
            observer.onCompleted()
        }
        return Disposables.create()
    }
}.flatMap { result -> Observable<Void> in
    print("Do something else (but only once)")
    return Observable.just(Void())
}.subscribe(
    onNext: {
        print("Next")
    },
    onCompleted: {
        print("Done")
    }
)

我得到的是

Starting request 1
Starting request 2
Starting request 3
Request 1 finished
Do something else (but only once)
Next
Request 2 finished
Do something else (but only once)
Next
Request 3 finished
Do something else (but only once)
Next
Done

整个过程在2秒后结束。我要的是

Starting request 1
Request 1 finished
Starting request 2
Request 2 finished
Starting request 3
Request 3 finished
Do something else (but only once)
Next
Done

整个序列应该在 6 秒后结束(因为它不是并行执行的)。

我用递归函数得到了它。但是有很多请求,这会导致我想避免的深度递归堆栈。

使用 concatMap 而不是 flatMap 以便一次发送一个而不是一次发送所有。在这里了解更多:

RxSwift’s Many Faces of FlatMap

然后要在之后只做一次,请使用 toArray()。这是一个完整的例子:

let objects = [1, 2, 3]

_ = Observable.from(objects)
    .concatMap { object -> Observable<Void> in
        return Observable.just(())
            .debug("Starting Request \(object)")
            .delay(.seconds(2), scheduler: MainScheduler.instance)
            .debug("Request \(object) finished")
    }
    .toArray()
    .flatMap { results -> Single<Void> in
        print("Do something else (but only once)")
        return Single.just(())
    }
    .subscribe(
        onSuccess: { print("done") },
        onError: { print("error", [=10=]) }
    )