【问题标题】:Swift Combine - combining publishers without waiting for all publishers to emit first elementSwift Combine - 合并发布者而不等待所有发布者发出第一个元素
【发布时间】:2021-03-02 08:53:27
【问题描述】:

我正在合并两个发布者:

let timer = Timer.publish(every: 10, on: .current, in: .common).autoconnect()
let anotherPub: AnyPublisher<Int, Never> = ...

Publishers.CombineLatest(timer, anotherPub)
    .sink(receiveValue: (timer, val) in { 
      print("Hello!")
} )

很遗憾,直到两个发布者都发出至少一个元素后才调用 sink。

有什么方法可以在不等待所有发布者的情况下调用接收器? 因此,如果任何发布者发出一个值,就会调用 sink 并将其他值设置为 nil。

【问题讨论】:

    标签: ios swift combine


    【解决方案1】:

    您可以使用prepend(…) 将值添加到发布者的开头。

    这是您的代码的一个版本,它将在两个发布者前面加上 nil

    let timer = Timer.publish(every: 10, on: .current, in: .common).autoconnect()
    let anotherPub: AnyPublisher<Int, Never> = Just(10).delay(for: 5, scheduler: RunLoop.main).eraseToAnyPublisher()
    
    Publishers.CombineLatest(
        timer.map(Optional.init).prepend(nil),
        anotherPub.map(Optional.init).prepend(nil)
    )
    .filter { $0 != nil && $1 != nil } // Filter the event when both are nil values
    .sink(receiveValue: { (timer, val) in
        print("Hello! \(timer) \(val)")
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2021-05-25
      • 2021-08-21
      • 1970-01-01
      • 2019-11-30
      • 2019-11-08
      相关资源
      最近更新 更多