Create an account or log in

Keep learning for free! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
6 Hrs
27 Min
16 Seg

Evitando doble subscribe

5/25
Resources

One of the main problems with observables is Callback Hell. Nesting N number of subscriptions, one inside the other, makes your code very difficult to maintain and read.

Solving Callback Problems

Using promises, you can solve this easily with async/await. But if we talk about observables, our best friend, the RxJS library, comes in to provide a solution.

A common example of this issue in Angular is like the following:

readAndUpdate(): void { // Example of callback hell this.apiService.getProduct(1) .subscribe(res => { this.apiService.updateProduct(1, { name: 'New product name' }) .subscribe(res2 => { // ...}); }); }); }

Where a request is being made for reading a product and immediately updating the product. Generating a subscribe within a subscribe.
Perhaps, up to two subscribes is acceptable, but it is not recommended to continue with that code structure and it is possible to solve it as follows.

import { switchMap } from 'rxjs/operators'; readAndUpdate(): void { // Solution callback hell this.apiService.getProduct(1) .pipe( switchMap(products => this.apiService.updateProduct(1, { name: 'New name' }) ) ) .subscribe(res => { // Updated product}); }

Importing switchMap from rxjs/operators, what this function does is to receive the data emitted by one observable, and immediately use it as input for the second one. This way, the code is cleaner and more professional.


Contributed by: Kevin Fiorentino.

Contributions 8

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Aqu铆 un peque帽o aporte adicional al funcionamiento del SwitchMap(), por Alan Buscaglia maestro del curso de Typescript con Angular

RxJS - SwitchMap() | Gentleman Programming

Recomiendo mucho ver el siguiente video para profundizar un poco mas en las estrategias para aplanar subscriptions de RXJS

https://www.youtube.com/watch?v=sxjpUNRU_tI&list=PL4vWncexIMYuvT5oCCGpShrRoM0hizLky&index=2

Es cuesti贸n de gustos, pero no me gusta tener c贸digo HTML al interior de un componente.

@Component({
  selector: 'app-category',
  template: `<app-products
    [products]="products"
    (loadMore)="onLoadMore()"
  ></app-products>`,
  styleUrls: ['./category.component.scss'],
})

bastante picante el tema de rxjs y sus operators 馃懡

Muy buen curso del profe.Apoyemoslo.

En mi trabajo tengo muchas situaciones as铆. Vengo aprendiendo RxJS con el paso del tiempo a como el proyecto me lo va requiriendo. Y no conoc铆a que era una mala pr谩ctica el tener un susbscribe dentro de otro.

Gracias!!

Se me ocurr铆a otra soluci贸n, usando el operador filter para no tener que hacer esa condici贸n, luego si el switchmap directo y por 煤ltimo el operador take, para que en teor铆a el subscribe se complete

primer comentario!