What is the difference between a Observable and a Subject in rxjs?

纵然是瞬间 提交于 2019-11-27 00:45:44

问题


i was going through this blog and to read about Observables and i couldnt figure out the difference between the Observable and a Subject


回答1:


In stream programming there are two main interfaces: Observable and Observer.

Observable is for the consumer, it can be transformed and subscribed:

observable.map(x => ...).filter(x => ...).subscribe(x => ...)

Observer is the interface which is used to feed an observable source:

observer.next(newItem)

We can create new Observable with an Observer:

var observable = Observable.create(observer => { 
    observer.next('first'); 
    observer.next('second'); 
    ... 
});
observable.map(x => ...).filter(x => ...).subscribe(x => ...)

Or, we can use a Subject which implements both the Observable and the Observer interfaces:

var source = new Subject();
source.map(x => ...).filter(x => ...).subscribe(x => ...)
source.next('first')
source.next('second')



回答2:


See rxjs document (more information and examples there): http://reactivex.io/rxjs/manual/overview.html#subject

What is a Subject? An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.

A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners.

and code, Subject extending Observable: https://github.com/ReactiveX/rxjs/blob/master/src/internal/Subject.ts#L22

/**
 * @class Subject<T>
 */
export class Subject<T> extends Observable<T> implements SubscriptionLike {
//...
}



回答3:


Observables

  1. They are cold: Code gets executed when they have at least a single observer.

  2. Creates copy of data: Observable creates copy of data for each observer.

  3. Uni-directional: Observer can not assign value to observable(origin/master).

  4. The code will run for each observer . If its a HTTP call, it gets called for each observer.

  5. if its a service we want to share among all the components, it wont have latest result all new subscribers will still subscribe to same observable and get value from scratch

  6. Unicast means can emit values from the observable not from any other component.

Subject

  1. They are hot: code gets executed and value gets broadcast even if there is no observer.

  2. Shares data: Same data get shared between all observers.

  3. bi-directional: Observer can assign value to observable(origin/master).

  4. If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject

  5. multicast, can cast values to multiple subscribers and can act as both subscribers and emmitter




回答4:


From another perspective, it is good to note that the subscription to an Observable re-execute the Observable function. This can lead performance issue if the data source is a service for instance.

If you want several subscribers to get the same value, you may need a Subject. For this, make sure that your subscription is set before the Subject subscribed to the data source. Otherwise, your process would be stuck.

More details here: https://javascript.tutorialhorizon.com/2017/03/23/rxjs-subject-vs-observable/




回答5:


Observable can inform only one observer, while Subject can inform multiple observers.




回答6:


Imagine if you have a stream of data coming into your application like in a websocket connection. You want a way to handle it. There is a few solution:

1. normal ajax request: This solution is not viable because it is not applicable to process push data. It is more of a pull then a push.

2. Promise: Also not good because you have to trigger them and they can only retrieve once. Also more of a pull then a push.

So in order to retrieve this data, in the old time, we do a long-polling. Which is where we set an interval function to retrieve that stream of data every 1 minute for an example. Though it works, it actually burdening resources like CPU and memory.

But now with option no 3,

3. Observable: You can subscribe and let the stream of data to come in non-stop until the function complete has been called.

Cool right ? But then there is another problem. What if you want to observe incoming data only once somewhere in your application. But you want to use that data simultaneously around your application when the data arrived. That is when and where you use Subject. You place subject.subscribe() at places you want to use throughout your application. When the data arrived, places where there is subject.subscribe() will process them simultaneously. But the observer must subscribe with the subject as its argument like this.

observer.subscribe(subject).

Example application is when you want to build a notification alert.

You cannot have multiple subscription of the same observable because chances are, each subscribers will received different input data. But with subject, all that subscribe() through subject will be retrieving the same data.

Another analogy is through magazine subscription. Each subscribers will received the magazine with their name on it. So, different subscription = different receiver name.(Normal Observable) But when you share with your friends, all of your friend would receive the same magazine with only your name on it.(Normal Observable with Subject)

This guy explain it very well with code example. You can check it out at https://javascript.tutorialhorizon.com/2017/03/23/rxjs-subject-vs-observable/

Hopefully this answer helps.



来源:https://stackoverflow.com/questions/47537934/what-is-the-difference-between-a-observable-and-a-subject-in-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!