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