Javatpoint Logo
Javatpoint Logo

RxJS multicast() Multicasting Operator

RxJS multicast() operator is a multicasting operator that returns an observable that emits the results of invoking a specified selector on items emitted by a ConnectableObservable that shares a single subscription to the underlying stream.

The RxJS multicast() operator is used to share the single subscription created with other subscribers.

Syntax:

Following is the syntax of the RxJS multicast() multicasting operator:

Or

Parameter Explanation

  • subjectOrSubjectFactory: It specifies the parameter passed to multicast. It is a subject or factory method that returns a subject, or it can be used to create an intermediate subject through which the source sequence's elements will be multicast to the selector function or Subject to push source elements into.
  • selector: It is an optional selector function that can use the multicasted source stream as many times as needed without causing multiple subscriptions to the source stream. Subscribers to the given source will receive all notifications of the source from the time of the subscription forward. Its default value is undefined.

Return value

The RxJS multicast() operator returns an observable that emits the results of invoking the selector on the items emitted by a ConnectableObservable that shares a single subscription to the underlying stream.

Let us see some examples of the RxJS multicast() operator to understand it clearly. Before seeing and understanding the working of a multicast() operator, let us first see how the multicast() operator works.

Example 1 (A simple observable with subscription)

Output:

After executing the above example, you will see the following result:

RxJS multicast() Multicasting Operator

In the above example, you can see that the output received from Sub1 and Sub2 are different. This is because when the subscriber gets called, the observable restarts and gives the fresh value available. But we need the subscribers getting called to have the same value.

Now, let's see how multicast works.

Example 2 (A simple multicast example)

Output:

After executing the above example, you will see the following result:

RxJS multicast() Multicasting Operator

In the above example, you can see that the same value is shared between the subscribers that are called.

Example 3 (Multicast example with standard Subject)

Output:

After executing the above example, you will see the following result:

RxJS multicast() Multicasting Operator

Example 4 (Multicast example with ReplaySubject)

Output:

After executing the above example, you will see the following result:

RxJS multicast() Multicasting Operator
Next TopicRxJS Operators




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA