[Fixed] how to run subscribe sequentially in observable

Issue

I want to run code sequentially but I was wondering how this works, for example, I have a method that includes two observable and some fields. I want to run the first observable completely then the next field values check and after that the last observable method:

// first it should be run completely --Step1

ontemplateSelectChanged(e){
const api = 'api/Sales/SaleTemplate/' + e;
this.dataSourceService
      .generateCustomApiDataList('sales', 'SaleTemplate', api)
      .dataList$.subscribe(
        (data) => {
this.saleTemplateDsDto.saleTemplateDto = data.rows['saleTemplateDto'];
});
// 2nd this should be check --step 2
if (myCondition){
// a lot of code here
    alert("we are here")
    }
    // this should be run at the end. --step 3
     const additionApi =
            'api/Sales/Addition/List?$filter=AdditionCode eq ' +
            additionCodefilterValue;
          this.dataSourceService
            .generateCustomApiDataList('sales', 'Addition', additionApi)
            .dataList$.subscribe(
              (data) => {            
                additionDtoList = data.rows;})
    }

but at the current stage step 2 completed first and step 3 next and at the end step 1. and sometimes it works fine. I read about concat here, I know this is a nice feature to get what I need but to be honest I couldn’t use it, and that only work if we have 2 observable over next each other(only step 3 and step 1).

Solution

There isn’t enough data to go around, but for a start you could use tap and switchMap operators. tap would be used for "step 2" and switchMap would be used to map to another observable (in your case "step 3", the 2nd HTTP request).

Try the following

import { switchMap, tap } from 'rxjs/operators';

ontemplateSelectChanged(e) {
  const api = 'api/Sales/SaleTemplate/' + e;
  this.dataSourceService
    .generateCustomApiDataList('sales', 'SaleTemplate', api)
    .dataList$
    .pipe(
      tap((data: any) => {
        this.saleTemplateDsDto.saleTemplateDto = data.rows['saleTemplateDto'];
        if (myCondition) {
          // a lot of code here
          alert("we are here")
        }
      }),
      switchMap(() => {
        const additionApi =
          'api/Sales/Addition/List?$filter=AdditionCode eq ' +
          additionCodefilterValue;
        return this.dataSourceService
          .generateCustomApiDataList('sales', 'Addition', additionApi)
          .dataList$;
      })
    ).subscribe(
      (data) => {
        additionDtoList = data.rows;
      }
    );
}

Leave a Reply

(*) Required, Your email will not be published