[英]CombineLatest multiple PassthroughSubject no output
let p1: PassthroughSubject<Int, Never> = .init()
let p2: PassthroughSubject<Bool, Never> = .init()
var pub1: AnyPublisher<Int, Never> {
return p1.eraseToAnyPublisher()
}
var pub2: AnyPublisher<Bool, Never> {
return p2.eraseToAnyPublisher()
}
var sub: AnyCancellable?
sub = Publishers.CombineLatest(pub1, pub2).sink(receiveValue: { output in
print("output: \(output)")
})
p1.send(4)
// nothing printed
p2.send(false)
// printed: output: (4, false)
why is there no output when p1 sends 4
?为什么 p1 发送4
时没有输出? How should I structure the code such that when either p1 pr p2 sends a value, there is an output?我应该如何构造代码,以便当 p1 pr p2 发送一个值时,有一个输出?
The combineLatest operator can't emit something until every publisher it is observing emits something (a publisher that hasn't emitted a value doesn't have a "latest value" to emit.) combineLatest 操作符在它观察到的每个发布者都发出某些东西之前不能发出某些东西(没有发出值的发布者没有要发出的“最新值”。)
As you mention in comments, one way to get around this is to use a CurrentValueSubject so that there is a "latest value" for each child publisher.正如您在评论中提到的,解决此问题的一种方法是使用 CurrentValueSubject 以便每个子发布者都有一个“最新值”。
Another way is to use .prepend
to emit a value for combineLatest
to use.另一种方法是使用.prepend
发出一个值供combineLatest
使用。
As in:如:
sub = Publishers.CombineLatest(pub1.prepend(0), pub2.prepend(false)).sink(receiveValue: { output in
print("output: \(output)")
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.