English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of Angular2Programming Object Observable in

Preface

The core provided by RxJs is the Observable object, which is a combination of asynchronous and event programming implemented using observable data sequences.
An asynchronous programming model similar to this is Promise, which is an asynchronous model based on state changes. Once a promise transitions from a pending state to a fulfilled or rejected state, it cannot be modified again. When the state changes, subscribers can only receive a single value; while Observable is an asynchronous programming model based on sequences, subscribers can continuously receive new values as the sequence changes. Moreover, Promise only provides a conversation mechanism and does not offer more operations to support complex result processing, whereas Observable provides a variety of operators to handle computation results, meeting the needs of complex application logic.

In actual programming, we mainly deal with three objects:Observable,observer,Subscription:

Let's take a look at how to use Observable with an element's click event as an example:

var clickStream = new Rx.Observable(observer => {
var handle = evt => observer.next(evt);
element.addEventListener('click', handle);
return () => element.removeEventListener('click', handle);
});
subscription = clickStream.subscribe(evt => {
console.log('onNext: ') + evt.id);
}, err => {
console.error('onError');
}, () => {
console.log('onComplete');
});
setTimeout(() => {
subscription.unsubscribe();
}, 1000);

If each event needs to be wrapped like this, wouldn't it be麻烦?Therefore, RxJs provides a convenient function: Observable.fromEvent to facilitate the connection of events.

Common link operators:concat, merge, combineLates, etc.

Projection operation:map, flatMap, flatMap needs to be introduced in detail

Filtering:filter, distinctUltilChanges

Operator classification:Operators by Categories

Error handling:catch, retry, finally

Decompression:debounce, throttle, sample, pausable

Reduction:buffer, bufferWithCount, bufferWithTime

To master the operators of Observable, you first need to learn to understand sequence diagrams:

Arrows represent sequences that change over time, such as continuously clicking the mouse on an element, where the circles represent the effects of the sequence on the outside, such as triggering an event callback each time an element is clicked. The numbers in the circles represent the information emitted externally, such as each event trigger having an event object that represents some information about this operation.

To use Observable to handle complex logic flexibly, you need to learn to use the operators it provides. I divide the operators into two categories: single sequence operations and composite sequence operations. Single sequence operations refer to operations performed on a single sequence, while composite sequence operations refer to operators that process two or more sequences. Composite sequence operations are relatively more difficult to understand.

Let's look at a single sequence operation, taking the map operation as an example:

The map operation converts the information emitted by each event in a sequence, as shown in the map above, which multiplies each emitted value by ten. Therefore, after the subscriber subscribes, the subscribed values are no longer the original123but rather the one after transformation10 20 30. Sequence diagrams can make it easier to understand the operations of Observable.

Let's look at a composite sequence operation, taking merge as an example

The purpose of the merge operation is to combine two independent sequences into one sequence. The original sequence1As time progresses,10Emit a at 0ms, in2Emit b at 00ms,3Emit c at 00ms, and its subscriber will4Received three values abc at 00ms; the sequence2At15Emit d at 0ms,25Emit e at 0ms,35Emit f at 0ms, and its subscriber will4Received three values def within 00ms. After merging, the new sequence will be4Received abcdef within 00ms (note the order).

Understanding of common operators:

Observable.range:Emit a sequence of a certain number of values

Observable.toArray: Convert all emitted values into an array when the sequence is completed

Observable.flatMap: Convert the elements in the original sequence stream into a new sequence stream, and merge this new sequence stream into the position of the elements in the original sequence.

Observable.startWith: It will set the first value of the Observable sequence

Observable.combineLatest: Similar to promiseAll, it will execute only after all sequences have results

Observable.scan: Aggregate the values emitted at each emission in the sequence, similar to reduce, which aggregates the values of the entire sequence and sends a final value when the sequence is completed

Observable.sample: Take a certain number of samples from a continuous sequence

Observable.merge:Merge multiple sequences into one, which can be used for OR

Observable.timestamp: Get the time of emission for each emitted value

Observable.distinctUntilChanged(compare, selector): selector extracts the key used for comparison, compare is used to compare two keys

Observable.takeWhile() Stop emitting data when the parameter is false

Summary

That's all for this article. I hope the content of this article can bring some help to your learning or work. If you have any questions, you can leave a message for communication.

You May Also Like