在 Swift / Combine 中按顺序执行两个 promise

Execute two promises in sequence in Swift / Combine

我有两个具有以下签名的函数:

import Combine

func firstCall() -> Future<Result<Void, Error>, Never> {
    return Future { promise in
        promise(.success(.success(())))
    }
}



func secondCall() -> Future<Result<Void, Error>, Never> {
    return Future { promise in
        promise(.success(.success(())))
    }
}


// Execute 1st call, then if it succeeds, execute the 2nd call

如何才能在第一个函数成功完成后才执行第二个函数?

理想情况下,我正在寻找这样的东西:

executeInSequence([firstCall(), secondCall()])
.onResult( { finalResult in
print(finalResult)
})

如果对调用站点有帮助,请随意稍微调整 API 签名。

更多信息:其中一个调用实际上是一个转换后的同步方法调用,其签名为:

func secondSynchronousCall() throws {
}

    private func secondCall() -> Future<Result<Void, Error>, Never> {
        return Future { [weak self] promise in
            do {
                try self?.secondSynchronousCall()
                promise(.success(.success(())))
            } catch {
                promise(.success(.failure(error)))
            }
        }
    }

在 Combine 中,Futures 只是专门的发布者。如果你与出版商打交道,你会做这样的事情:

let cancellable = firstCall()
.tryMap { result in
    try result.get()
}
.flatMap { _ in
    secondCall()
}
.tryMap { result in
    try result.get()
}
.sink { completion in
    print(completion)
} receiveValue: { _ in
    print("reveiveValue")
}

你可以写得更简洁,但是,我建议首先简化你的输出和错误类型,正如评论中已经指出的那样:

例如:

func firstCall2() -> Future<Void, Error> {
    return Future { promise in
        promise(.success(()))
        //promise(.failure(MyError()))
    }
}

func secondCall2() -> Future<Void, Error> {
    return Future { promise in
        promise(.success(()))
    }
}

然后:

let cancellable2 = firstCall2()
.map(secondCall2)
.sink { completion in
    print(completion)
} receiveValue: { _ in
    print("reveiveValue")
}