实例方法
multicast(subject:)
提供主题以将元素传递给多个订阅者。
声明
func multicast<S>(subject: S) -> Publishers.Multicast<Self, S> where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output
参数
subject
将元素传递给下游订阅者的主体。
详述
当您有多个下游订阅者时使用多播发布者,但您希望上游发布者只处理每个事件的一个 Subscriber/receive(_:)
调用。当上游发布者正在做你不想重复的昂贵工作时,这很有用,比如执行网络请求。
与 Publisher/multicast(_:)
相比,此方法生成一个发布者,该发布者在所有下游订阅者之间共享提供的 Subject
。
以下示例使用序列发布者作为计数器发布三个随机数,由 Publisher/map(_:)-99evh
运算符生成。它使用Publisher/multicast(subject:)
运算符和PassthroughSubject
来向两个订阅者中的每一个共享相同的随机数。因为多播发布者是 ConnectablePublisher
,所以发布仅在调用 ConnectablePublisher/connect()
之后开始。
let pub = ["First", "Second", "Third"].publisher
.map( { return ($0, Int.random(in: 0...100)) } )
.print("Random")
.multicast(subject: PassthroughSubject<(String, Int), Never>())
cancellable1 = pub
.sink { print ("Stream 1 received: \($0)")}
cancellable2 = pub
.sink { print ("Stream 2 received: \($0)")}
pub.connect()
// Prints:
// Random: receive value: (("First", 78))
// Stream 2 received: ("First", 78)
// Stream 1 received: ("First", 78)
// Random: receive value: (("Second", 98))
// Stream 2 received: ("Second", 98)
// Stream 1 received: ("Second", 98)
// Random: receive value: (("Third", 61))
// Stream 2 received: ("Third", 61)
// Stream 1 received: ("Third", 61)
在此示例中,输出显示 Publisher/print(_:to:)
运算符仅接收每个随机值一次,然后将该值发送给两个订阅者。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift Result.Publisher multicast(_:)用法及代码示例
- Swift Result.Publisher merge(with:_:_:)用法及代码示例
- Swift Result.Publisher merge(with:_:_:_:_:_:_:)用法及代码示例
- Swift Result.Publisher map(_:_:_:)用法及代码示例
- Swift Result.Publisher merge(with:_:)用法及代码示例
- Swift Result.Publisher map(_:)用法及代码示例
- Swift Result.Publisher min()用法及代码示例
- Swift Result.Publisher merge(with:_:_:_:_:_:)用法及代码示例
- Swift Result.Publisher merge(with:_:_:_:_:)用法及代码示例
- Swift Result.Publisher max()用法及代码示例
- Swift Result.Publisher merge(with:_:_:_:)用法及代码示例
- Swift Result.Publisher measureInterval(using:options:)用法及代码示例
- Swift Result.Publisher map(_:_:)用法及代码示例
- Swift Result.Publisher mapError(_:)用法及代码示例
- Swift Result.Publisher makeConnectable()用法及代码示例
- Swift Result.Publisher zip(_:_:_:)用法及代码示例
- Swift Result.Publisher tryLast(where:)用法及代码示例
- Swift Result.Publisher sink(receiveCompletion:receiveValue:)用法及代码示例
- Swift Result.Publisher tryCompactMap(_:)用法及代码示例
- Swift Result.Publisher print(_:to:)用法及代码示例
- Swift Result.Publisher sink(receiveValue:)用法及代码示例
- Swift Result.Publisher eraseToAnyPublisher()用法及代码示例
- Swift Result.Publisher setFailureType(to:)用法及代码示例
- Swift Result.Publisher first(where:)用法及代码示例
- Swift Result.Publisher output(at:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Result.Publisher multicast(subject:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。