實例方法
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 Result.Publisher multicast(subject:)用法及代碼示例
- 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(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。