multicast(_:)
Applies a closure to create a subject that delivers elements to subscribers.
Declaration
func multicast<S>(_ createSubject: @escaping () -> S) -> Publishers.Multicast<Self, S> where S : Subject, Self.Failure == S.Failure, Self.Output == S.OutputParameters
- createSubject:
A closure to create a new Subject each time a subscriber attaches to the multicast publisher.
Discussion
Use a multicast publisher when you have multiple downstream subscribers, but you want upstream publishers to only process one receive(_:) call per event. This is useful when upstream publishers are doing expensive work you don’t want to duplicate, like performing network requests.
In contrast with multicast(subject:), this method produces a publisher that creates a separate Subject for each subscriber.
The following example uses a sequence publisher as a counter to publish three random numbers, generated by a map(_:) operator. It uses a multicast(_:) operator whose closure creates a PassthroughSubject to share the same random number to each of two subscribers. Because the multicast publisher is a ConnectablePublisher, publishing only begins after a call to 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)In this example, the output shows that the print(_:to:) operator receives each random value only one time, and then sends the value to both subscribers.