I am using Angular 2 and RxJS 5.
Is there any difference between these two:
And which should be used first? Thanks
isOpen$ = new BehaviorSubject<boolean>(true);
and
isOpen$ = BehaviorSubject.create(true);
A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities. An observable can be created from both Subject and BehaviorSubject using subject.
The main difference between an Observable and a Subject is that a plain Observable by default is unicast. It means that each subscribed Observer owns an independent execution of the Observable. On the other hand, Subjects are multicast. A Subject is like an Observable, but it can multicast to many Observers.
While the BehaviorSubject and ReplaySubject both store values, the AsyncSubject works a bit different. The AsyncSubject is aSubject variant where only the last value of the Observable execution is sent to its subscribers, and only when the execution completes.
BehaviorSubject
doesn't have a create
method, so I am guessing that is being exposed by the Subject
base class.
Use the constructor.
You should be using the constructor of the BehaviorSubject
in this case. The create
method is used to combine an Observer
and Observable
.
For instance, you could convert a WebSocket
into a Subject
by doing:
var webSocket = new WebSocket(url);
var observer = Observer.create(next => webSocket.send(JSON.stringify(next)));
var observable = Observable.fromEvent(webSocket, 'message', m => JSON.parse(m.data));
var subject = Subject.create(observer, observable);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With