如果当前 andThen 中的值为 nil,我该如何继续执行下一个 andThen?

How do I proceed to the next andThen if the value in the current andThen is nil?

我已将多个调用链接到同一个 Completable,如下所示:

self.viewModel.setParameter(parameter: lockReleaseTime)
                    .andThen(Completable.deferred { self.viewModel.setParameter(parameter: lockRelease) })
                    .andThen(Completable.deferred { self.viewModel.setParameter(parameter: lockVoltage) })
                    .andThen(Completable.deferred { self.viewModel.setParameter(parameter: lockPowered) })
                    .andThen(Completable.deferred { self.viewModel.setParameter(parameter: lockPowered) })
                    .andThen(Completable.deferred { self.viewModel.setParameter(parameter: lockInstall) })
                    .andThen(Completable.deferred { self.viewModel.setParameter(parameter: lockKick) })
                    .subscribe(onCompleted: {
                        print("-- Done setting parameter")
}).disposed(by: self.disposeBag)

这里的问题是 arguments 可以为 nil(lockRelease、lockVoltage 等);如果是,我只想跳过当前的 andThen 并继续进行下一个 andThen,就像这样:

.andThen(Completable.deferred {
    guard let lockRelease = lockRelease else {
        Completable.skipToNextAndThen
     }
                        
    return self.viewModel.setParameter(parameter: lockRelease) })

是否可以这样做?

你的 skipToNextAndThen 叫做 .empty()。此外,在这种情况下不需要 deferreds。如:

func example() {
    setOptionalParameter(parameter: lockReleaseTime)
        .andThen(setOptionalParameter(parameter: lockRelease))
        .andThen(setOptionalParameter(parameter: lockVoltage))
        .andThen(setOptionalParameter(parameter: lockPowered))
        .andThen(setOptionalParameter(parameter: lockInstall))
        .andThen(setOptionalParameter(parameter: lockKick))
        .subscribe(onCompleted: {
            print("-- Done setting parameter")
        })
        .disposed(by: disposeBag)
}

func setOptionalParameter(parameter: Param?) -> Completable {
    guard let parameter = parameter else { return .empty() }
    return viewModel.setParameter(parameter: parameter)
}

此外,您可以使用 concat:

而不是所有 andThen
Completable.concat(
    setOptionalParameter(parameter: lockReleaseTime),
    setOptionalParameter(parameter: lockRelease),
    setOptionalParameter(parameter: lockVoltage),
    setOptionalParameter(parameter: lockPowered),
    setOptionalParameter(parameter: lockInstall),
    setOptionalParameter(parameter: lockKick)
)
.subscribe(onCompleted: {
    print("-- Done setting parameter")
})
.disposed(by: disposeBag)

另外,我希望他们真的不必按顺序一次完成一个。如果没有,您可以使用 zip:

Completable.zip(
    setOptionalParameter(parameter: lockReleaseTime),
    setOptionalParameter(parameter: lockRelease),
    setOptionalParameter(parameter: lockVoltage),
    setOptionalParameter(parameter: lockPowered),
    setOptionalParameter(parameter: lockInstall),
    setOptionalParameter(parameter: lockKick)
)
.subscribe(onCompleted: {
    print("-- Done setting parameter")
})
.disposed(by: disposeBag)