Learn RxJS
Search…
publish

signature: publish() : ConnectableObservable

Share source and make hot by calling connect.

Examples

Example 1: Connect observable after subscribers
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { publish, tap } from 'rxjs/operators';
4
5
//emit value every 1 second
6
const source = interval(1000);
7
//do nothing until connect() is called
8
const example = publish()(source.pipe(
9
//side effects will be executed once
10
tap(_ => console.log('Do Something!')),
11
));
12
13
/*
14
source will not emit values until connect() is called
15
output: (after 5s)
16
"Do Something!"
17
"Subscriber One: 0"
18
"Subscriber Two: 0"
19
"Do Something!"
20
"Subscriber One: 1"
21
"Subscriber Two: 1"
22
*/
23
const subscribe = example.subscribe(val =>
24
console.log(`Subscriber One: ${val}`)
25
);
26
const subscribeTwo = example.subscribe(val =>
27
console.log(`Subscriber Two: ${val}`)
28
);
29
30
//call connect after 5 seconds, causing source to begin emitting items
31
setTimeout(() => {
32
example.connect();
33
}, 5000);
Copied!

Additional Resources