Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subject vs AnonymousSubject

What's the difference between Subject and AnonymousSubject in RxJS 5? I've searched the internet but didn't find any info about AnonymousSubject.

I've found an example on the web

Subject.create(observer, observable);

Looking into rxjs source code I saw that this creates and AnonymousSubject. Can you also come up with an example when is good to use AnonymousSubject?

like image 333
Doua Beri Avatar asked Feb 09 '17 22:02

Doua Beri


People also ask

What is AnonymousSubject?

You can use AnonymousSubject to define an operator that returns a hot observable. Usually the Observable will be a Subject too, for example a BehaviorSubject . On the Observer side, the onNext method will "do something" with the value it receives and push to the destination Subject.

What is difference between subject and observable?

subject: you can send to it and receive from it. Observable: you can receive from it only. In another words, In subject you can subscribe to it and you can use it to broadcast to other subscribers any time and anywhere in code.

What is difference between subject and BehaviorSubject?

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 a subject in RxJS?

A subject in RxJS is a special hybrid that can act as both an observable and an observer at the same time. This way, data can be pushed into a subject, and the subject's subscribers will, in turn, receive that pushed data.


2 Answers

The AnonymousSubject doesn't subscribe itself to the source Observable. It just connects the source and destination.

I don't know what a typical use-case for AnonymousSubject looks like but it's used inside Subject.lift().

Also see: RxJs Subject.subscribe method not working as expected

like image 53
martin Avatar answered Oct 04 '22 06:10

martin


You can use AnonymousSubject to define an operator that returns a hot observable. Usually the Observable will be a Subject too, for example a BehaviorSubject.

On the Observer side, the onNext method will "do something" with the value it receives and push to the destination Subject. For example an the observer could accept a boolean value for "is the network connection available", try connecting to a server when the network connection becomes available, and push true to a BehaviorSubject if the attempt to connect succeeds. This AnonymousSubject would tell you upon subscription whether you are connected to the server.

like image 28
Paolo Bonzini Avatar answered Oct 04 '22 08:10

Paolo Bonzini