Search code examples
angularrxjsobservableobservers

Rxjs observable versus observer 'semantics'


since a few weeks I use Observables quite often and it is a true joy to have this in the toolbox.

However, I cannot seem to grasp the semantics/terminology illustrated by the following construct (just a theoretical example):

const o = Observable.create((observer: Observer<boolean>) => {
 observer.next(true);
 observer.error(false);
});

I understand that you need to pass in an argument to the anonymous function to make it happen, but why is this called an Observer of type Observer and why would you call next() and error() on this observer? Intuitively to me it is the observable that emits the values and pushes it to the observer. The above construct seems to turn this around.

Basically, would it not be more logical to have the following pseudo code:

const o = Observable.create(() => {
 this.next(true);
 this.error(false);
});

or, even more clearly:

const o = Observable.create(next: () => {... return true;}, error: () => { return false;});

Maybe a very rookie question, but I would love to get some insight.

Thanks!


Solution

  • Observable-Observer pattern is a Push mechanism, means that it is the mission of Observable to notify Observer. Observable needs a reference to Observer to notify it about new emitions. Observable callbacks such as onNext and onError are the bridge between Observable-Observer so such callbacks exists in Observer and Observable will call them.