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.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 operatorsBefore 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
from
range
- 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
, interval
fromEvent
- Data needs to be emitted manually and not automatically closed:
create
, (also Rx.Subject.create
)
2.2 Conversion
- 1:1 effects:,,,,,
map
mapTo
flatMap
scan
expand
pluck
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
- 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.
switchMapTo
The same is switchMap
concatMap
true of concatMapTo
mergeMap
contrast mergeMapTo
.
mergeMap
Compared to switchMap
, the found data will be flattened into source, not discarded.
- 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
- 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)
window
and buffer
different when the source is sent each time it is innerobservable
window
vs vs vs windowCount
windowTime
windowWhen
with buffer
similar
- 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 FiltrationThe 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 CombinationMake 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
zip
And 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
find
And 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 CalculationAfter 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
- RXJS Official website-http://reactivex.io/rxjs/
- RXJS code-HTTPS://GITHUB.COM/REACTIVEX/RXJS
- Interaction diagram of common RXJS methods-http://rxmarbles.com/
- RXHJS Tutorial-http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/toarray.html
- Scheduler-https://mcxiaoke.gitbooks.io/rxdocs/content/scheduler.html
- Original address: https://yq.aliyun.com/articles/65027