Learn RxJS
Search…
BehaviorSubject

Requires an initial value and emits the current value to new subscribers

πŸ’‘ If you want the last emitted value(s) on subscription, but do not need to supply a seed value, check out ReplaySubject instead!
​​
​
​

Examples

Example 1: Simple BehaviorSubject

1
// RxJS v6+
2
import { BehaviorSubject } from 'rxjs';
3
​
4
const subject = new BehaviorSubject(123);
5
​
6
// two new subscribers will get initial value => output: 123, 123
7
subject.subscribe(console.log);
8
subject.subscribe(console.log);
9
​
10
// two subscribers will get new value => output: 456, 456
11
subject.next(456);
12
​
13
// new subscriber will get latest value (456) => output: 456
14
subject.subscribe(console.log);
15
​
16
// all three subscribers will get new value => output: 789, 789, 789
17
subject.next(789);
18
​
19
// output: 123, 123, 456, 456, 456, 789, 789, 789
Copied!

Example 2: BehaviorSubject with new subscribers created on mouse clicks

1
// RxJS v6+
2
import { BehaviorSubject, fromEvent, interval, merge } from 'rxjs';
3
import { map, tap, mergeMap } from 'rxjs/operators';
4
​
5
const setElementText = (elemId, text) =>
6
(document.getElementById(elemId).innerText = text.toString());
7
const addHtmlElement = coords =>
8
(document.body.innerHTML += `
9
<div
10
id=${coords.id}
11
style="
12
position: absolute;
13
height: 30px;
14
width: 30px;
15
text-align: center;
16
top: ${coords.y}px;
17
left: ${coords.x}px;
18
background: silver;
19
border-radius: 80%;"
20
>
21
</div>`);
22
​
23
const subject = new BehaviorSubject(0);
24
​
25
const click$ = fromEvent(document, 'click').pipe(
26
map((e: MouseEvent) => ({
27
x: e.clientX,
28
y: e.clientY,
29
id: Math.random()
30
})),
31
tap(addHtmlElement),
32
mergeMap(coords => subject.pipe(tap(v => setElementText(coords.id, v))))
33
);
34
​
35
const interval$ = interval(1000).pipe(
36
tap(v => subject.next(v)),
37
tap(v => setElementText('intervalValue', v))
38
);
39
​
40
merge(click$, interval$).subscribe();
Copied!

Additional Resources

Last modified 6mo ago