SwiftCombine-组合发布者,无需等待所有发布者发出第一个元素

我正在合并两个出版商:

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。

回答

您可以使用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)")
})


以上是SwiftCombine-组合发布者,无需等待所有发布者发出第一个元素的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>