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

Lijin Durairaj picture Lijin Durairaj · Nov 28, 2017 · Viewed 27.1k times · Source

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

Answer

ZahiC picture ZahiC · Nov 28, 2017

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')