In the following code, is the subscriber object in the anonymous function call in new Observable(function(subscriber) a wrapper for the observer object?
const observer = {
next: (data: any) => console.log('Observer got a next value: ', data),
error: (err: any) => console.error('Observer got an error: ' + err),
complete: () => console.log('Observer got a complete notification'),
};
const observable = new Observable(function(subscriber) {
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
setTimeout(() => {
subscriber.next(4);
subscriber.complete();
}, 1000);
});
observable.subscribe(observer);
subscriber in function(subscriber) {...} is the name of the parameter of the function which is invoked when the subscribe method is called on the observable.
Let's see step by step.
First you create the Observable like this
new Observable(function(subscriber) {...})
What you are doing is you are passing a function to the constructor method. That function is stored in the observable instance you have created.
Then you invoke the subscribe function on the observable you have created above like this
observable.subscribe(observer)
What you do here is to ask the observable to execute the function passed at construction time with the observer as value of the parameter. observer in this case is an object of type Observer.
The observer and subscriber are the same type of object (in typescript they'd have the same interface).
The observer is being defined in code. The subscriber is a parameter.
Consider
a: number = 10; vs function(b:number){...
We know the value of a, but b doesn't have q concrete value until the function is called. In fact, you could call this function with the value in a. a does not wrap b as such.