链接 Combine.Publisher 并在完成时调用完成

Chaining Combine.Publisher and calling completion when finished

我正在尝试按顺序调用多个发布者,并在最后一个发布者完成后调用 completionBlock。所有 return 类型的发布者都是 AnyPublisher<Void, Error>。与下面的解决方案相比,我可以使用 .flatMapPublishers 中提供的一些其他功能来完成吗?

private var firstObserver: AnyCancellable?
private var secondObserver: AnyCancellable?

public func setup() {
    firstObserver = Manager.firstPublisher()
        .sink(receiveCompletion: {_ in}, receiveValue: {[weak self] _ in
            self?.secondObserver = Manager.secondPublisher()
                .sink(receiveCompletion: {_ in}, receiveValue: {[weak self] _ in
                    self?.completionBlock()
                }
        })
}

如果发布者相互依赖,您应该使用 .flatMap 链接。如果没有,您可以使用 .append 代替。无论哪种方式,如果所有这些发布者都是一次性发布者(他们都在一个值后发送完成),那么当所有发布者都被触发时,链将被有序地拆除。

示例 1:

    Just(1)
        .flatMap { Just(([=10=],2)) }
        .flatMap { Just(([=10=].0, [=10=].1, 3)) }
        .sink(receiveCompletion: {print([=10=])},
              receiveValue: {print([=10=])})
        .store(in:&storage)
        // (1,2,3) as a tuple, then finished

示例 2:

    Just(1).append(Just(2).append(Just(3)))
        .sink(receiveCompletion: {print([=11=])},
              receiveValue: {print([=11=])})
        .store(in:&storage)
    // 1, then 2, then 3, then finished