Look at an example:
const myObservable = of(1, 2, 3);
// 创建一个观察者对象-Observer(处理next、error、complete回调)
const myObserver = {
next: x => console.log('Observer got a next value: ' + x),
error: err => console.error('Observer got an error: ' + err),
complete: () => console.log('Observer got a complete notification'),
};
// 通过Observable的subscribe函数,观察者去订阅可观察者的消息
myObservable.subscribe(myObserver);
Call the subscribe method of Observable and pass in an observer object containing a callback function:
The last two parameters are undefined:
In the toSubscriber function, because nextOrObserver is the object I manually passed in, the first two IF conditions are not met:
Enter the default implementation and create a new Subscriber object:
Subscriber is a subclass of Subscription:
In the constructor of our current Subscriber, create a SafeSubscruber instance: this is passed in as the parent subscriber
EmptyObserver is imported from ./Observer:
As can be seen from the implementation of SafeSubscriber, the function names next, error, and complete of the passed Observer object are all hard-coded and must conform to this naming convention:
The Object.create() method creates a new object and uses the existing object to provide the __proto__ of the newly created object.
Execute subscribe:
The sink's destination contains the complete, next, and error logic passed in by the application:
As you can see here, the logic of subscribe is to traverse all Observable parameters, call the next method of observer in turn, and finally call the complete method again:
next calls the private _next method:
this._next calls this.destination.next:
Finally, the next method passed in by the application programmer is called:
The final output:
To get more original articles by Jerry, please follow the public account "Wang Zixi":