You don't have access to this class

Keep learning! 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
10 Hrs
56 Min
34 Seg

Evitando el callback hell

15/23
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.

How to solve Callback Hell

Using promises, you can solve this problem easily with async/await. But if we talk about observables, our best friend, the RxJS library, comes in to provide its 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.

How to solve this Callback Hell problem?

Maybe up to two subscribers 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 { // Callback hell solution 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 use it as input for the second one. This way, the code is cleaner and more professional.

Learn more about RxJS

Another alternative provided by RxJS is the possibility of manipulating several observables at the same time. With promises, you can make use of Promise.all([]) to perform N asynchronous processing in parallel and get their results.
Very similarly, in RxJS you can do the following.

import { zip } from 'rxjs'; readAndUpdate(): void { // Grouping observables into the same subscribezip( this.apiService.getProduct(1), this.apiService.updateProductPATCH(1, { name: 'New name' }) ) .subscribe(res => { const get = res[0]; const update = res[1]; }); }); }

By importing the zip function, you can create an array of observables and subscribe to all of them at the same time. Differentiating by the index of each one the result of the operation that they executed to obtain it.

In this example, index 0 has the result of the read and index 1 that of the update.


Contribution created by: Kevin Fiorentino.

Contributions 19

Questions 3

Sort by:

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

Sería un buen complemento en la escuela de Angular, un curso de Rxjs.

Un curso de Rxjs, plis. 0_o

Mi reacción durante y despues de esta clase

Muy buena la clase y la explicación del profesor, pero quiero aportar de que hay otros métodos que nos ayudan a realizar peticiones en paralelo en los observables, solo que hay que tener claro su uso y estos son: forkJoin, combineLatest y withLatestFrom.
Para que puedan observar las diferencias dejo por acá este link (https://www.digitalocean.com/community/tutorials/rxjs-operators-forkjoin-zip-combinelatest-withlatestfrom) donde se evidencian las diferencias de cada uno de ellos.

Para obtener los elementos del array (para el caso de Zip) cuando se conoce la posición y el tipo de dato, es más sencillo hacerlo así

const [read, update] = response;

https://rxjs.dev/
Documentacion de Rxjs!

esa función de ZIP será de gran ayuda para optimizar el tiempo de respuesta de mi portal.
Excelente aporte

Rxjs es mi pastor

el profe Nicolas nombra NGRX en lugar RXJS, si alguien tiene la duda son cosas diferentes, NGRX es el “redux” de Angular que tambien funciona con observables (RXJS)

Es necesario tener presente que el uso de switchMap cancela el resultado del observable anterior, esto es, en caso de que se disparen dos peticiones dentro de un switchMap, este solo obtendrá el resultado del último,

Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable .>
RxJs.Dev/switchMap

Si lo que se quiere es enviar escuchar más de una observable a la vez y al mismo tiempo usar este resultado para encadenar un nuevo request a manera de callback se puede hacer uso de mergeMap, este permite unir observables sin priorizar uno sobre el otro.

Mi cerebro hizo Booom!!! jajaj

Zip , similar a PromiseAll()

Cada que avanzo en el curso me doy cuenta de lo increible y asombroso que es el Framework, tantas formas de solucionar problemas y todo tan claro con Nico, no me la creo jaja.

Dejo los codigos de los servicios que hice

  fetchReadAndUpdate(id: string, dto:UpdateProductDTO) {
    return zip(
      this.getProduct(id),
      this.update(id, dto)
    );
  }

  getProductAndupdate(id: string, dto:UpdateProductDTO){
    return this.getProduct(id)
      .pipe(
        switchMap((product) => this.update(product.id, dto))
      )
  }

Y tambien como los llamo del lado del componente:

  readAndUpdate(id: string){
    this.productsService.getProductAndupdate(id, {title: 'change'})
      .subscribe(data => {
        console.log(data);
      });

    this.productsService.fetchReadAndUpdate(id, {title: 'change'})
    .subscribe(response => {
      const product = response[0];
      const update = response[1];
    })

  }

Excelente clase.

Siii, Yo también creo que es muy importante un curso de programación reactiva con RxJS.

Wow que clase!!
En verdad las cosas que aprendi en esta clase me ayudaran mucho en mi crecimiento profecional

excelente clase,Nico como siempre.