我遇到了一些组合问题,在https://developer.apple.com/documentation/combine/publisher中遇到了“与多个订阅者一起工作”部分:
func multicast<S>(() -> S) -> Publishers.Multicast<Self, S>
func multicast<S>(subject: S) -> Publishers.Multicast<Self, S>
但是,当我尝试确认发送给多个订阅者时需要多播的假设时,我发现在尝试此操场代码时不需要这样做(修改自https://github.com/AvdLee/CombineSwiftPlayground/blob/ master/Combine.playground/Pages/Combining%20Publishers.xcplaygroundpage/Contents.swift)(在 Xcode 版本 11.0 beta 3 (11M362v) 中的 10.14.5 上运行):
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
所以似乎不需要多播来解决多个订阅者。还是我错了?
那么,这些多播功能是做什么用的,我将如何使用它们呢?一些示例代码会很好。
谢谢,
拉斯