Learn RxJS
Search…
multicast

signature: multicast(selector: Function): Observable

Share source utilizing the provided Subject.

Examples

Example 1: multicast with standard Subject
1
// RxJS v6+
2
import { Subject, interval } from 'rxjs';
3
import { take, tap, multicast, mapTo } from 'rxjs/operators';
4
5
//emit every 2 seconds, take 5
6
const source = interval(2000).pipe(take(5));
7
8
const example = source.pipe(
9
//since we are multicasting below, side effects will be executed once
10
tap(() => console.log('Side Effect #1')),
11
mapTo('Result!')
12
);
13
14
//subscribe subject to source upon connect()
15
const multi = example.pipe(multicast(() => new Subject()));
16
/*
17
subscribers will share source
18
output:
19
"Side Effect #1"
20
"Result!"
21
"Result!"
22
...
23
*/
24
const subscriberOne = multi.subscribe(val => console.log(val));
25
const subscriberTwo = multi.subscribe(val => console.log(val));
26
//subscribe subject to source
27
multi.connect();
Copied!
Example 2: multicast with ReplaySubject
1
// RxJS v6+
2
import { interval, ReplaySubject } from 'rxjs';
3
import { take, multicast, tap, mapTo } from 'rxjs/operators';
4
5
//emit every 2 seconds, take 5
6
const source = interval(2000).pipe(take(5));
7
8
//example with ReplaySubject
9
const example = source.pipe(
10
//since we are multicasting below, side effects will be executed once
11
tap(_ => console.log('Side Effect #2')),
12
mapTo('Result Two!')
13
);
14
//can use any type of subject
15
const multi = example.pipe(multicast(() => new ReplaySubject(5)));
16
//subscribe subject to source
17
multi.connect();
18
19
setTimeout(() => {
20
/*
21
subscriber will receieve all previous values on subscription because
22
of ReplaySubject
23
*/
24
const subscriber = multi.subscribe(val => console.group(val));
25
}, 5000);
Copied!

Additional Resources

Last modified 2yr ago