头图

Notice:

  1. flatMap is an alias for mergeMap.
  2. If only one internal subscription can be activated at a time, use switchMap.
  3. If the order of emission and subscription of internal observables is important, use concatMap.

MergeMap is an excellent use case when you need to flatten an internal observable but want to manually control the number of internal subscriptions.

For example, when using switchMap, each inner subscription completes when the source emits, ie only one active inner subscription is allowed at any time. In contrast, mergeMap allows multiple internal subscriptions to be activated simultaneously. Therefore, one of the most common use cases for mergeMap is requests that should not be cancelled, which are considered writes rather than reads.

A typical example is the amount of different line items in the SAP e-commerce cloud shopping cart, which can be increased or decreased in parallel.

Note that if these writes must remain in order, concatMap is a better choice. Such as database write operations.

Since mergeMap maintains multiple active internal subscriptions at once, it can cause memory leaks due to long-lived internal subscriptions. A basic example is if using internal timers or dom event streams are mapped to observables. In these cases, if you still want to use mergeMap, a good way is to use another operator to manage the completion of the inner subscription, such as take or takeUntil. Of course, you can also use the concurrent parameter to limit the number of subscriptions within an activity.

See an example:

 import { fromEvent, of } from 'rxjs';
import { mergeMap, delay } from 'rxjs/operators';

// faking network request for save
const saveLocation = location => {
  return of(location).pipe(delay(500));
};
// streams
const click$ = fromEvent(document, 'click');

click$
  .pipe(
    mergeMap((e: MouseEvent) => {
      return saveLocation({
        x: e.clientX,
        y: e.clientY,
        timestamp: Date.now()
      });
    })
  )
  // Saved! {x: 98, y: 170, ...}
  .subscribe(r => console.log('Saved!', r));

saveLocation is a function that wraps any incoming input parameters into an Observable, and this Observable does not emit data immediately, but delays it for 500 milliseconds.

mergeMap receives a function as an input parameter. The input parameter of this function is the element contained in the Observable linked to mergeMap through the pipe, namely MouseEvent; the data type returned by project is a new Observable, which contains the X and Y coordinates of the screen click and the current timestamp.

The final output produced:


注销
1k 声望1.6k 粉丝

invalid