Oibreoirí RxJS a chlaochlaíonn, a scagann, agus a chomhcheanglaíonn sruthanna Observable. Is iad na ceithre oibreoirí flapála — an rud is tábhachtaí agus is mearbhall — na cinn is thábhachtaí, agus baineanns siad le hObservables-of-Observables (mar shampla, glaoch HTTP atá spreagtha ag gach astarraingt de shruth eile).
Oibreoirí claochlaitheocha/scagtha coitianta
import { map, filter, tap, debounceTime, distinctUntilChanged, catchError } from "rxjs/operators";
source$.pipe(
map(x => x * 2), // transform each value
filter(x => x > 10), // keep values passing a test
tap(x => console.log(x)), // side effect, doesn't change the stream
debounceTime(300), // wait for a pause before emitting (search inputs)
distinctUntilChanged(), // ignore consecutive duplicates
);
Na ceithre oibreoirí flapála (an chuid dhraíochta)
Nuair is gá go spreagfaidh gach luach ó fhoinse oibreoirí eile Observable (cosúil le iarratas HTTP), ní mór duit an Observable inmheánach a "fhlapáil". Is éagsúil iad na ceithre ar conas iad a dhéileáil le forshíoladh:
switchMap → cancels the previous inner Observable when a new value arrives
mergeMap → runs all inner Observables concurrently (no cancellation)
concatMap → queues them, runs one at a time in order
exhaustMap → ignores new values while an inner Observable is still running
Cathain a úsáid gach ceann
// switchMap — type-ahead search: cancel the stale request when the user types again
this.searchInput.valueChanges.pipe(
debounceTime(300),
switchMap(query => this.api.search(query)) // only the LATEST query's result matters
).subscribe(results => this.results = results);
// mergeMap — fire independent requests in parallel (order doesn't matter)
from(ids).pipe(mergeMap(id => this.api.get(id)));
// concatMap — operations that MUST run in order (e.g. sequential saves)
actions$.pipe(concatMap(action => this.api.save(action)));
// exhaustMap — ignore repeated clicks while a login is in flight
this.loginClick$.pipe(exhaustMap(() => this.auth.login())); // ignore spam clicks
Mnemóinic
switchMap = "switch to the new one" (cancel old) → search
mergeMap = "merge all" (parallel) → independent requests
concatMap = "concatenate" (sequential) → ordered operations
exhaustMap = "exhaust current first" (ignore new) → prevent double-submit
Cén fáth a bhfuil sé tábhachtach
Is iad na hoibreoirí flapála ar na huirlisí RxJS is thábhachtaí — agus is minic a dhéantar iad a mhíúsáid — in Angular.
Baineann rogha thuathalach gnéithe fíora: má úsáideann tú mergeMap do thóraighe, taispeántar torthaí sean-aimseartha (gan chur ar ceal); má úsáideann tú switchMap do shábhálacha seicheamhúla, chuireann siad ar ceal iad ar foluain.
Tá sé riachtanach a bheith i bhfios gur cuireann switchMap ar ceal (an-oiriúnach do thóraighe), go bhfuil concatMap socraithe, go bhfuil mergeMap ag soláthar go comhthreomhar, agus go bhfuil exhaustMap ag bac ar dhúbailte, ar bhealach éigeantach do dhéileáil cheart le asincronach in aon chód Angular a bhfuil go leor RxJS ann.
