Search code examples
angularrxjsobservable

How to subscribe to observable one after another


I have a list of GraphQL request for example

const req1 = this.updateUserGQL
        .mutate(
          { input: {name: 'x'} }
        )
.
.
.
const reqn = this.updateUserGQL
        .mutate(
          { input: {name: 'y'} }
        )

const requests = [req1, req2, req3, ... reqn]

For my use case, I need to subscribe the requests one after another i.e first subscribe req1, then subscribe req2 only if req1 finished or gave an error and so on. How can I do this?


Solution

  • You need the concat rxjs operator to ensure each observable is completed before proceeding to the next one.

    import { concat } from 'rxjs';
    
    concat(
      req1, 
      req2, 
      req3, 
      ... reqn
    )
    .subscribe(/* Action */);