Sobes.tech
Middle

RxJS task: optimize the chain of operators (pipe with filter, toLowerCase, switchMap). Explain why switchMap is used, how it differs from concatMap and exhaustMap. Which operator is better for processing payment requests?

sobes.tech AI

Answer from AI

In RxJS, the switchMap operator is used to switch to a new inner Observable upon receiving a new value, canceling the previous inner Observable. This is useful when you need to process only the latest request, such as in autocomplete search.

concatMap processes all inner Observables sequentially, waiting for each to complete before starting the next. This guarantees order but may delay processing new values.

exhaustMap ignores new values if the previous inner Observable has not yet completed. This prevents overlapping requests but may miss new data.

For processing payment requests, it is better to use exhaustMap or concatMap:

  • exhaustMap — if it is important not to initiate a new payment until the previous one is finished (to avoid duplicates).
  • concatMap — if you need to process all requests sequentially, without skipping any.

switchMap is not suitable here because it cancels the previous request, which could lead to lost payments.

Example with switchMap:

input$.pipe(
  filter(text => text.length > 2),
  map(text => text.toLowerCase()),
  switchMap(query => http.get(`/search?q=${query}`))
)

Here, switchMap cancels the previous request on new input.

For payments:

paymentRequests$.pipe(
  exhaustMap(request => processPayment(request))
).subscribe();

This guarantees that while a payment is being processed, new requests are ignored.

RxJS task: optimize the chain of operators (pipe with… - sobes.tech