实例方法
multicast(_:)
应用闭包来创建将元素传递给订阅者的主题。
声明
func multicast<S>(_ createSubject: @escaping () -> S) -> Publishers.Multicast<Self, S> where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output
参数
createSubject
每次订阅者附加到多播发布者时创建一个新的
Subject
的闭包。
详述
当您有多个下游订阅者时使用多播发布者,但您希望上游发布者只处理每个事件的一个 Subscriber/receive(_:)
调用。当上游发布者正在做你不想重复的昂贵工作时,这很有用,比如执行网络请求。
与 Publisher/multicast(subject:)
相比,此方法生成一个发布者,该发布者为每个订阅者创建一个单独的 Subject
。
以下示例使用序列发布者作为计数器发布三个随机数,由 Publisher/map(_:)-99evh
运算符生成。它使用 Publisher/multicast(_:)
运算符,其闭包创建一个 PassthroughSubject
以将相同的随机数共享给两个订阅者中的每一个。因为多播发布者是 ConnectablePublisher
,所以发布仅在调用 ConnectablePublisher/connect()
之后开始。
let pub = ["First", "Second", "Third"].publisher
.map( { return ($0, Int.random(in: 0...100)) } )
.print("Random")
.multicast { 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", 9))
// Stream 2 received: ("First", 9)
// Stream 1 received: ("First", 9)
// Random: receive value: (("Second", 46))
// Stream 2 received: ("Second", 46)
// Stream 1 received: ("Second", 46)
// Random: receive value: (("Third", 26))
// Stream 2 received: ("Third", 26)
// Stream 1 received: ("Third", 26)
在此示例中,输出显示 Publisher/print(_:to:)
运算符仅接收每个随机值一次,然后将该值发送给两个订阅者。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift Optional.Publisher multicast(subject:)用法及代码示例
- Swift Optional.Publisher mapError(_:)用法及代码示例
- Swift Optional.Publisher merge(with:_:_:)用法及代码示例
- Swift Optional.Publisher map(_:_:)用法及代码示例
- Swift Optional.Publisher map(_:_:_:)用法及代码示例
- Swift Optional.Publisher merge(with:_:_:_:_:_:_:)用法及代码示例
- Swift Optional.Publisher measureInterval(using:options:)用法及代码示例
- Swift Optional.Publisher max()用法及代码示例
- Swift Optional.Publisher merge(with:_:_:_:)用法及代码示例
- Swift Optional.Publisher merge(with:_:_:_:_:)用法及代码示例
- Swift Optional.Publisher map(_:)用法及代码示例
- Swift Optional.Publisher merge(with:_:)用法及代码示例
- Swift Optional.Publisher min()用法及代码示例
- Swift Optional.Publisher makeConnectable()用法及代码示例
- Swift Optional.Publisher merge(with:_:_:_:_:_:)用法及代码示例
- Swift Optional.Publisher reduce(_:_:)用法及代码示例
- Swift Optional.Publisher tryDrop(while:)用法及代码示例
- Swift Optional.Publisher debounce(for:scheduler:options:)用法及代码示例
- Swift Optional.Publisher breakpoint(receiveSubscription:receiveOutput:receiveCompletion:)用法及代码示例
- Swift Optional.Publisher catch(_:)用法及代码示例
- Swift Optional.Publisher tryAllSatisfy(_:)用法及代码示例
- Swift Optional.Publisher zip(_:_:_:)用法及代码示例
- Swift Optional.Publisher sink(receiveValue:)用法及代码示例
- Swift Optional.Publisher scan(_:_:)用法及代码示例
- Swift Optional.Publisher throttle(for:scheduler:latest:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Optional.Publisher multicast(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。