What is the difference between a Observable and a

2019-02-13 17:24发布

问题:

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:

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/