After reading an article about observables, I came across some code that puzzled me.
I am struggling to comprehend the following lines ->
return this._subscribe({
onNext: onNext,
onError: onError || (() => {}),
onCompleted: onCompleted || (() => {})
});
1) This syntax is new to me, can someone explain what it does exactly?
When using typeof, it indicates that it's an object, but it seems like an object within a function, which seems odd to me.
2) Since I couldn't grasp the code, I experimented and found that if I return
return {
onNext: onNext,
onError: onError || (() => {}),
onCompleted: onCompleted || (() => {})
}
The code fails to reach Point Two (refer to -> // PointTwo below, after "return new Observable((obs)")
I believe the answer to the second question might be linked to the first one.
export class Observable<T> {
/** Internal implementation detail */
private _subscribe: any;
/**
* @constructor
* @param {Function} subscribe is the function that is called when the
* observable is subscribed to. This function is given a subscriber/observer
* which provides the three methods on the Observer interface:
* onNext, onError, and onCompleted
*/
constructor(subscribe: any) {
if (subscribe) {
this._subscribe = subscribe;
};
}
// public api for registering an observer
subscribe(onNext: any, onError?: any, onCompleted?: any) {
if (typeof onNext === 'function') {
return this._subscribe({
onNext: onNext,
onError: onError || (() => {}),
onCompleted: onCompleted || (() => {})
});
} else {
throw new Error("Please provide a function")
}
}
static of(...args): Observable {
return new Observable((obs) => {
//pointTwo
args.forEach(val => {
console.log("3")
obs.onNext(val)
});
obs.onCompleted();
return {
unsubscribe: () => {
// just make sure none of the original subscriber's methods are never called.
obs = {
onNext: () => {},
onError: () => {},
onCompleted: () => {}
};
}
};
});
}
}
Observable.of(42).subscribe((num) => {console.log("number is -> " + num)})