Here’s an example:
const myObservable = of(1.2.3);
// Create an Observer object -Observer(handle next, error, complete callback)
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'),};Observables subscribe to Observable messages via the Subscribe function of Observable
myObservable.subscribe(myObserver);
Copy the code
Subscribe (Observable), passing in an observer containing the callback:
The last two parameters are undefined:
In the toSubscriber function, because nextOrObserver is the object I passed in manually, the first two IF conditions are not met:
Go to the default implementation and create a Subscriber object:
Subscriber is a subclass of Subscription:
In our current Subscriber constructor, create an instance of SafeSubscruber: this is passed in as parent Subscriber
EmptyObserver is imported from./Observer:
As you can see from SafeSubscriber’s implementation, the next, error, and complete function names passed in to the Observer are hard-coded and must conform to this naming convention:
The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object.
Perform the subscribe:
Sink’s destination contains the complete, next, error logic passed in by the application:
As you can see, the logic of subscribe is to loop through all Observable parameters, call observer next, and then call complete:
Next calls the private _next method:
Enclosing _next calls this. Destination. Next:
The final call to the next method passed in by the application programmer:
Final output:
For more of Jerry’s original articles, please follow the public account “Wang Zixi “: