Operator之数据合并(Mixing elements from multiple publishers)

combineLatest/CombineLatest3/CombineLatest4

combineLatest把2个publisher的数据进行合并,正常情况下,2个publisher中任何一个产生新的数据,就会把数据合并后输出,遇到错误pipline立刻终止。

  • 合并2个publisher

  • 输出的数据为元组

var cancellables = Set<AnyCancellable>()
let firstPublisher = PassthroughSubject<Int, MyCustomError>()
let secondPublisher = PassthroughSubject<String, MyCustomError>()

firstPublisher
    .combineLatest(secondPublisher)
    .sink(receiveCompletion: { completion in
        print("结束了")
        switch completion {
        case .finished:
            print("完成")
        case .failure(let error):
            print("错误:\(error.localizedDescription)")
        }
    }, receiveValue: { someValue in
        print("someValue: \(someValue)")
    })
    .store(in: &cancellables)

firstPublisher.send(1)
secondPublisher.send("a")
firstPublisher.send(2)

打印结果:

someValue: (1, "a")
someValue: (2, "a")

merge/merge3/merge4/merge5/merge6/merge7/merge8/MergeMany

merge用于合并2-8个publisers的数据成一个publisher,combineLatest会把每个publiser的latest数据组合成一个元组,而merge只要接受到新数据就输出。

MergeMany用于合并多个publisers,写法都一样,参考combineLatest即可

zip/zip3/zip4

zip和combineLatest非常相似,默认情况下会返回成组的数据,但他们最大的不同在于zip不会使用latest值,它使用的是新值。

var cancellables = Set<AnyCancellable>()
let pub1 = PassthroughSubject<Int, Never>()
let pub2 = PassthroughSubject<Int, Never>()

pub1
    .zip(pub2)
    .sink(receiveCompletion: { completion in
        print("结束了")
        switch completion {
        case .finished:
            print("完成")
        case .failure(let error):
            print("错误:\(error.localizedDescription)")
        }
    }, receiveValue: { someValue in
        print("someValue: \(someValue)")
    })
    .store(in: &cancellables)

pub1.send(1)
pub1.send(2)
pub1.send(3)
pub2.send(4)
pub2.send(5)

使用.zip返回的是(1,4)和(2,5)
而使用.combineLatest返回的则是(3,4)和(3,5)

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1