Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'new BehaviorSubject' and 'BehaviorSubject.create'

Tags:

angular

rxjs5

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);
like image 701
Hongbo Miao Avatar asked May 13 '16 19:05

Hongbo Miao


People also ask

What is the difference between BehaviorSubject vs subject?

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.

What is the difference between BehaviorSubject and Observable?

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.

What is difference between subject and Observable?

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.

What is the difference between Behavioursubject subject ReplaySubject and async subject?

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.


1 Answers

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);
like image 118
paulpdaniels Avatar answered Oct 30 '22 18:10

paulpdaniels