Contents

multicast(subject:)

Provides a subject to deliver elements to multiple subscribers.

Declaration

func multicast<S>(subject: S) -> Publishers.Multicast<Self, S> where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output

Parameters

  • subject:

    A subject to deliver elements to downstream subscribers.

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(_:), this method produces a publisher that shares the provided Subject among all the downstream subscribers.

The following example uses a sequence publisher as a counter to publish three random numbers, generated by a map(_:) operator. It uses a multicast(subject:) operator with 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(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)

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.

See Also

Working with multiple subscribers