BehaviourSubject

This Subject emits the following:

  • the initial value
  • the values emitted generally
  • last emitted value.

methods:

next()
complete()
constructor([start value])
getValue()
1
2
3
4
import { BehaviorSubject } from 'rxjs';

let behaviorSubject = new BehaviorSubject(42);

behaviorSubject.subscribe((value) =>   console.log('behaviour subject',value) );
console.log('Behaviour current value',behaviorSubject.getValue());
behaviorSubject.next(1);
console.log('Behaviour current value',behaviorSubject.getValue());
behaviorSubject.next(2);
console.log('Behaviour current value',behaviorSubject.getValue());
behaviorSubject.next(3);
console.log('Behaviour current value',behaviorSubject.getValue());

// emits 42
// current value 42
// emits 1
// current value 1
// emits 2
// current value 2
// emits 3
// current value 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Business case

This is quite similar to ReplaySubject. There is a difference though, we can utilize a default / start value that we can show initially if it takes some time before the first values starts to arrive. We can inspect the latest emitted value and of course listen to everything that has been emitted. So think of ReplaySubject as more long term memory and BehaviourSubject as short term memory with default behavior.