Rxjs Simple Introduction

Source: Internet
Author: User
Tags emit

Summary: # RXJS simple Getting Started > RXJS full name Reactive Extensions for Javascript,javascript's responsive extension, the response is to turn data, states, events, and so on over time into observable sequences ( Observable Sequence), and then subscribe to the changes in those Observable objects in the sequence, and once the changes are made, the various transformations and operations arranged in advance are performed **RXJS for the asynchronous scenario, the front end

Rxjs Simple Introduction

RXJS Full name reactive Extensions for Javascript,javascript's responsive extension, the response is to turn data, states, events, and so on over time into observable sequences (Observable Sequence) , and then subscribe to the changes of those observable objects in the sequence, and once the changes are made, the various transformations and actions that are arranged in advance are performed

RXJS applies to asynchronous scenarios, which are interface requests, browser events, and custom events in the front-end interaction. Using RXJS brings us an unprecedented development experience.

    1. The specification of unified asynchronous programming, whether it is promise, Ajax or events, is encapsulated as if 序列(Observable Sequence) there is a change in the asynchronous link, the observation sequence can intercept the changed information.
    2. The front-end business layer and the presentation layer are decoupled, such as the presentation layer does not need a relationship to specify event triggering and DOM-independent processing logic. The business layer can also assemble the relationships between multiple asynchronous logic in an asynchronous operation without exposing it to the presentation layer. The presentation layer is concerned with the data changes in the process of asynchronous operation.
    3. RXJS Development Business layer has the characteristics of high elasticity, high stability and high real-time performance.

      Needless to say, this document combines examples of simulated scenarios to illustrate the commonly used methods of RXJS and the combination of relationships through a dummy description.

1. Let ' s Go

RXJS applies the Observer pattern, which contains 2 important instances: Observer observer and subject are observed, multiple observer are registered to subject, and when the subject function is triggered, a registered OBSERVAB list is notified, Notify each other of their response to the observed change information.

1.1 Quick Start
  1. A few example concepts from the official website to RXJS
    • Observable : Observable data series.
    • Observer : The Observer instance used to determine when to observe the specified data.
    • Subscription : Watch the data sequence to return the subscription instance.
    • Operators :   Observable operation method, including conversion data series, filtering, etc., all Operators The parameter that is accepted by the method is the value of the last data change sent , and the method return value we call the launch new data change .
    • Subject : The object being observed.
    • schedulers : Controls scheduling concurrency, that is, when observable accepts subject change responses, the response can be set by scheduler, and the currently built-in response can be called Object.keys (rx.subject) view.
  2. Our most commonly used and most concerned observable, four lifecycles: Create, subscribe, execute, destroy.
    • Creates a obervable that returns the observed 序列源实例 , which does not have the ability to send data, by contrast, by new Rx.Subject creating the 观察对象实例 ability to send data sources.
    • 序列源实例Response method When new data changes are emitted by a subscription sequence (callback method)
    • The action of the response is actually the execution of the observable
    • 序列源实例it can be destroyed and automatically destroyed when the subscription method has an error.
    • 序列源实例catchmethod can capture errors that occur with the subscription method, and 序列源实例 can accept the catch return value from the method as a new序列源实例
  3. Learn the simplest examples

  4. 5.0.0-rc.1import Rx from ' Rxjs ',//emit 1 from Promiseconst Source = Rx.Observable.fromPromise (new Promise (resolve = Resolve (1)));//add to the valueconst example = Source.map (val = val +);//output:11const subscribe = example.su Bscribe (val = Console.log (val));

    Mastering by Code Observable ,   Observer ,   Subscription ,   Operators ,   Subject and schedulers relationship

    Import Rx from ' Rxjs ';/** rx.observable is a Observable Rx.Observable.create create sequence source sources, there are several ways to create a source, such as, from,  Frompromise such as observer is observer observer, only in the Rx.Observable.create creation method can be obtained, the other creation method built-in observer and inaccessible Observer.next emission data Update Source.map where map is one of the methods of operators, the method call returns a new Source1 Source1.subscribe is the subscription, which is the response method when the data is updated. At the same time, return to the subscription instance subscription subscription.next immediate response (different from transmitting) static data, this time will not go through ' Operators ' processing! The source created by Rx.Observable.create or Rx.Subject.create is not automatically closed, and other ways are automatically destroyed if no sequence changes are detected source.*/const Source =  RX.OBSERVABLE.CREATE (Observer = {observer.next (' foo '); SetTimeout (() = Observer.next (' Bar '), 1000);}); Const SOURCE1 = source.map (val = ' Hello ${val} '); const SUBSCRIPTION = Source1.subscribe (value = Console.log (value ); Subscription.next (' foo1 ');//foreach is similar to subscribe, which is the same as implementing the subscription effect, until promise can monitor subscription complete and failed exceptions. The log print is not comlete because source does not complete shutdown, triggering calls Observer.complete () const PROMISE = Source1.foreach (value = Console.log ( Value) Promise.then (() = Console.log (' complete '), (err) = consOle.log (Err));/** output:hello foo foo1 hello foo Hello bar hello bar*//** new subject Create a Watcher instance, as with source Subscr  The Ibe method, the meaning and function of the expression, is the same as the response method when the transmitting data is changed. Subject.next immediately launches data changes, acting with Observer.next note foo1 is the last output, because Rx.Scheduler.async is specified when the source is created and is an asynchronous scheduler that is executed asynchronously in response to data processing. */rx.observable.of (' foo1 ', Rx.Scheduler.async). Subscribe (value = Console.log (value)); Const SUBJECT = new subject ( Const SOURCE2 = subject.map (val = ' Hello ${val} '); const SUBSCRIPTION = Source1.subscribe (value = Console.log (VA Lue)); Subject.next (' foo '); Subscription.next (' Bar ');/** output:hello foo bar foo1*/

      

      1. 1.2 Learn to see RXJS interaction diagram

        Each link in the interaction diagram represents a sequence of data, each of which represents a change in each launch, and the last line represents the final output of the data series.

    Take Combinelastest for example:

      • Each line above the method is a source (data sequence instance)
      • The new source returned after method invocation under method
      • Combinelastest represents the combination of each source, once the transmit data changes, must get the remaining source of the latest value (when asynchronous then wait until all get the latest value), the combination of new data, as the new source of data changes emitted.source1: ————————①——————————②——————————③————————————④—————————⑤——————————|——> source2: ———————————?————————?————————————?—————————————————————?—————————|——> combineLastest(source1, source2, (x, y) => x + y) source: ———————(①?)—(②?)—(②?)—————(③?)—(③?)———(④?)————(⑤?)—(⑤?)——|——>
    2. Example Method operators

    Before the Operators method call, the received parameter is source, the new source is returned, and the following is a simple summary of the use of RXJS parties in the personal learning process.

    2.1 Create
      • The data update is automatically closed after launch:,,,, from fromPromise of fromrange
      • Do not launch direct shutdown:empty
      • To close after throwing an exception:throw
      • No data is emitted or closed:never
      • Keep the transmit data and do not close automatically: timer , intervalfromEvent
      • Data needs to be emitted manually and not automatically closed: create , (also Rx.Subject.create )
    2.2 Conversion
    1. 1:1 effects:,,,,, map mapTo flatMap scan expandpluck
      • map, Source = Source1.map (func) means that Source1 is processed by the Func function each time the data is emitted, returning the new value as the source of the data emitted
      • mapTo, unlike map , func changes to a static value
      • flatMap, when the emitted data is a source, it is also a source received in the response method of the subscription (it is reasonable to emit what data to respond to what data, but if we want to receive the response method is the source of the emission data), Flatmap is the ability to allow the transmission of data is a source, while in response to receive is the source of the data sent, after we call **source Ping * *
      • scan, Source = Source1.scan (func, InitialValue), the source data for each launch is the result of a combination of the source's previous transmit data and the data currently emitted by the source1 (depending on the Func, which is generally added), InitialValue first launch, source not fired before, using InitialValue as data from previous launch
      • expand, and the scan difference is that when the Func return value is a source, the data received by the Func is source打平 after the transmit data. * * Ideal for polling long polling * *
      • pluck, each time the data is emitted, gets the value of the specified attribute in the data as the emitted data of the source
    2. 1:n Effect:concat,concatAll,concatMap,concatMapTo,merge,mergeAll,mergeMap,mergeMapTo,switchMap,switchMapTo
      • concat, concatAll and merge , mergeAll belonging to the combination type, put in this to say better to reflect its effect.
      • concat, Source = Source1.concat (Source2) indicates that the order in which the source emits the array is, when Source1 or source2 emits the data, the source is fired. However, source2 emission data is triggered only when the source1 is fired and closed (Source1 is not sending data).
      • concatAll, unlike concat , all the emitted data will be flattened (if the data is source), and then decide which data to launch next.
      • concatMap, Source = Source1.concatmap (source2) means that source1 each time the data is emitted, all transmit data of SOURCE2 is obtained, MAP returns multiple pending data, and the first data change is emitted sequentially.
      • concatMapTo, unlike concatMap , map processing takes SOURCE2 data as the return result
      • switchMap, and the concatMap difference is the order of the data to be emitted after the map, concatMap in Source1 each launch SOURCE2 all transmit data received, as Source1 before the next launch, all the data between the transmission. The switchMap Source2 will determine whether the data of all the transmitting data has a launch time later than the time of Source1 next launch, find out.
      • switchMapToThe same is switchMap concatMap true of concatMapTo mergeMap contrast mergeMapTo .
      • mergeMapCompared to switchMap , the found data will be flattened into source, not discarded.
    3. N:1 Effect: buffer ,   bufferCount ,   bufferTime ,   Bufferwhen
      • buffer , Source = Source1.buffer (Source2) indicates that Source1 is referenced by Source2, In the source2 between the 2 transmit data for a time period, the source emits data only once, and the data is a combination of the data that the source1 was supposed to emit during that time period.
      • For example, Source1 originally emitted data every 1 seconds, Source2 is each 2 second transmit data, Source = Source1.buffer (Source2), Then source emits data every 2 seconds (an array of 2 numeric values emitted within 2 seconds of Source1)
      • bufferCount , Source = Source1.buffercount (count, Start), Count represents source1 each 3 transmit data as the source of the first emission data, after the launch, to source1 the current combination of the launch data starting start to calculate the next launch data need to combine the starting data.
      • bufferTime , the source1 emission data for a period of time as the source of the first emission data
      • bufferwhen , the default result is divided into 2 segments, Each transmit data as source, respectively
    4. 1:source effect:,,, groupBy window windowCount windowTime ,windowWhen
      • groupBy, Source = Source1.groupby (func), which represents all transmit data for source1, is divided into multiple segments by Func, each of which is sent as source data (here the data is just the new source, which you can understand as inner Observable instances)
      • windowand buffer different when the source is sent each time it is innerobservable
      • windowvs vs vs windowCount windowTime windowWhen with buffer similar
    5. 1:sources Effect:partition
      • partition, sources = Source1.partition (func), according to the Func bar all of the source1 emission data segments, each segment composed of a source, and finally get the sources array
    2.3 Filtration

    The filter of source does not make any changes to the transmit data, only reduces the number of times the source is emitted, so it is much simpler to understand, just a simple classification

      • Anti-jitter (for a period of time only to take the latest data as a single emission data, other data cancel the launch): debounce , debounceTime , throttle (and the debounce only difference is to take a period debounce of time the latest, and throttle ignore this time, found that the new value is sent),throttleTime
      • Deduplication (overlapping emission data only goes to the first data as the transmit data, the other same data cancels the launch): distinct ,distinctUntilChanged
      • Positioning (according to the condition values to go to one or part of several data as the corresponding emission data, other cancellation of the launch):,,,,,,, elementAt first last filter take takeLatst takeUntil takeWhile ,
      • Skip (conditionally remove eligible, take the remaining value as each transmit data):,, skip skipUntil skipWhile , ignoreElements (Ignore all, equal empty )
      • Sample: sample , Source=source1.sample (SOURCE2), in order to source2 emission data to discover the latest Source1 emission data, as the source of the emission data, the personal feel should belong to * * conversion * * Classification, the official website put on the * * Filter * *
    2.4 Combination

    Make a source group to synthesize a new souce

      • concat, concatAll and merge , mergeAll , in * * converted * * Classification spoke of
      • combineLastest, Source = Source1.combinelastest (Source2, func), Source1 and Source2 once the data is emitted, func triggers, gets source1 and source2 the latest launch data, returns the new data, The emitted data as source.
      • combineAll, same combineLastest ,, Source = Sources.combineall ()
      • forkJoin, Source = Rx.Observable.forkJoin (sources), all sources are closed after acquiring their latest array of transmit arrays, as the source of the emitted data
      • zipAnd forkJoin the difference is that zip sources all have to send data when combined to send data as an array of source, and sources any source is closed, then take the value of the last emitted by source.
      • zipAll, concat the same pairconcatAll
      • startWith, Source = Source1.startwith (value), which indicates that the first transmit data is injected at the front of the Source1
      • withLastestFrom, soruce = Source1.withlastestfrom (Source2, Func), which represents source1 each time the data is emitted, gets source2 the latest emitted data, and if present, Func processes the resulting new array as the source of the emitted data
    2.5 judgement
      • findAnd the designation of the findIndex emission data and the emission data of the subscript (the number of times sent), should be put in * * Filter * * Classification only reasonable
      • isEmpty, every , and include so on, judging whether it is true, the result of judgment as the emission data of source
    2.6 Error Handling
      • catch, the Operators exception that occurs during the invocation of source can be catch captured and the new source can be returned, because the current source of the exception is automatically destroyed.
      • retry, Source = Source.retry (times), all launches of source, repeat several times.
      • retryWhen, according to the conditions to decide how many times, only if the condition is false only to jump out of the loop.
    2.7 Tools
      • do, before each response to the subscription, can be Source.do (func), do some advance processing and other actions, such as printing the data emitted.
      • delay, delayWhen each time the data is sent, it is deferred for a certain interval before it is sent.
      • observeOn, set scheduler, that is, the response of the transmitting data, schedulers Detailed view of the address, here does not explain, the project is not used much.
      • subcribeOn, timeInterval set Sheduler
      • toPromise, source turns into promise, can achieve source.subscribe effect by Promise.then
      • toArray, the source of all emitted data, composed of array output.
    2.8 Calculation

    After the calculation of all emitted data of source, the data obtained as the emission data of the new source are calculated as follows: max ,,, min count reduce , average et

    2.9 Other
      • cache, Source = Source1.cache (1); the shared Source1 subscription result, that is, the transmit data received by the response method is the same regardless of the source subscription.
      • The result of sharing the source subscription is important, as * * * * * Combine multiple source combinations, including Sourcea, and Sourcea also need to subscribe to their results separately, without the cache case, Sourcea will produce 2 subscription, That is, 2 subscription instances, but we would prefer to be able to notify all of the combination sourcea source when the sourcea is changed.
      • publish, Publishsource = Source.publish (), delays the work of the source's subscription, that is, source does not emit data, but waits until the Publishsource.connect () is called before developing the transmit data. The effect and delay very similar, the difference is can control the suitable launch.
      • share, when the source subscribes multiple times, each response is do called multiple times, and by share merging the response, the source launches a data update, and multiple responses do are invoked once when the response is processed.
    Resources
      1. RXJS Official website-http://reactivex.io/rxjs/
      2. RXJS code-HTTPS://GITHUB.COM/REACTIVEX/RXJS
      3. Interaction diagram of common RXJS methods-http://rxmarbles.com/
      4. RXHJS Tutorial-http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/toarray.html
      5. Scheduler-https://mcxiaoke.gitbooks.io/rxdocs/content/scheduler.html
      6. Original address: https://yq.aliyun.com/articles/65027

Rxjs Simple Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.