Swift Combine - 在不等待所有发布者发出第一个元素的情况下合并发布者
Swift Combine - combining publishers without waiting for all publishers to emit first element
我要合并两个发布商:
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 { [=10=] != nil && != nil } // Filter the event when both are nil values
.sink(receiveValue: { (timer, val) in
print("Hello! \(timer) \(val)")
})
我要合并两个发布商:
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 { [=10=] != nil && != nil } // Filter the event when both are nil values
.sink(receiveValue: { (timer, val) in
print("Hello! \(timer) \(val)")
})