banner
Tomorrow

Tomorrow

不骄不躁
twitter

RxJS —— Observer Observer

Observer is a consumer of the values delivered by Observable. It is a set of callbacks for each type of notification that Observable can deliver: next, error, complete.

const observer = {
    next: (x) => console.log('Observer got a value: ' + x),
    error: (err) => console.error('Observer got an error: ' + err),
    complete: () => console.log('Observer got a complete notification'),
};

To use an Observer, provide it to the subscribe method of Observable:

observable.subscribe(observer);

An observer is just an object with three callbacks, one for each type of notification that an Observable may deliver.

Observers in RxJS can also be partial. If you don't provide one of the callbacks, the execution of the Observable will still proceed normally, except that certain types of notifications will be ignored because they have no corresponding callback in the observer.

Here is an observer without the complete callback:

const observer = {
    next: (x) => console.log('Observer got a value: ' + x),
    error: (err) => console.error('Observer got an error: ' + err),
}

When subscribing to an Observable, you can also provide only the next callback as a parameter without attaching it to an observer object, for example:

observable.subscribe(x => console.log('Observer got a value: ' + x));

Inside observable.subscribe, it will create an Observer object with the callback parameter as the next handler.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.