作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 https://developer.apple.com/documentation/combine/publisher 中的“与多个订阅者合作”部分遇到了一些合并问题。 :
func multicast<S>(() -> S) -> Publishers.Multicast<Self, S>
func multicast<S>(subject: S) -> Publishers.Multicast<Self, S>
enum FormError: Error { }
let usernamePublisher = PassthroughSubject<String, FormError>()
let passwordPublisher = PassthroughSubject<String, FormError>()
let validatedCredentials = Publishers.CombineLatest(usernamePublisher, passwordPublisher)
.map { (username, password) -> (String, String) in
return (username, password)
}
.map { (username, password) -> Bool in
!username.isEmpty && !password.isEmpty && password.count > 12
}
.eraseToAnyPublisher()
let firstSubscriber = validatedCredentials.sink { (valid) in
print("First Subscriber: CombineLatest: Are the credentials valid: \(valid)")
}
let secondSubscriber = validatedCredentials.sink { (valid) in
print("Second Subscriber: CombineLatest: Are the credentials valid: \(valid)")
}
// Nothing will be printed yet as `CombineLatest` requires both publishers to have send at least one value.
usernamePublisher.send("avanderlee")
passwordPublisher.send("weakpass")
passwordPublisher.send("verystrongpassword")
First Subscriber: CombineLatest: Are the credentials valid: false
Second Subscriber: CombineLatest: Are the credentials valid: false
First Subscriber: CombineLatest: Are the credentials valid: true
Second Subscriber: CombineLatest: Are the credentials valid: true
最佳答案
PassthroughSubject 不是一个很好的测试示例,因为它是一个类并为您提供引用语义。因此,在一个简单的情况下,两个订阅者可以直接订阅它并在主体发出一个值时同时接收相同的值。
但这里有一个更好的测试用例(灵感来自关于 Cocoa With Love 的讨论):
let pub1 = Timer.publish(every: 1, on: .main, in: .default).autoconnect()
let sub = CurrentValueSubject<Int,Never>(0)
let scan = sub.scan(10) {i,j in i+j}
pub1.sink { _ in let i = sub.value; sub.value = i+1 }.store(in:&storage)
scan.sink { print("a", $0) }.store(in:&storage)
delay(3) {
scan.sink { print("b", $0) }.store(in:&self.storage)
}
sink
时,这给出了一个非常奇怪的结果。作为此管道的新订阅者出现:
a 10
a 11
a 13
a 16
b 13
a 20
b 17
a 25
b 22
a 31
b 28
a 38
b 35
a
和
b
正在获得彼此不同的一系列数字,实际上是因为
scan
是一个结构。如果我们希望它们获得相同的数字,我们可以使用多播:
let scan = sub.scan(10) {i,j in i+j}.multicast {PassthroughSubject()}.autoconnect()
a 10
a 11
a 13
a 16
a 20
b 20
a 25
b 25
multicast
,因为你可以通过说
.share()
来完成同样的事情。反而。我不清楚
multicast
之间的区别是什么和
share
.
关于Swift 组合 : What are those multicast functions for and how do I use them?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918286/
我是一名优秀的程序员,十分优秀!