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
?
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.
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.
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.
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.
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
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.
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