Home > Back-end >  Execute methods one by one in Angular and RxJS
Execute methods one by one in Angular and RxJS

Time:10-20

this.userClient.getUser(userName)
.pipe(
    concatMap(
        user => { 
            this.user = user;
            return this.userClient.setStatus(this.user.id, 'banned');
        }
    ),
    concatMap(
        user => {
            //set property...
            return this.userClient.deleteImg(user.img);
        }
    ),
    mergeMap(
        user => {
            this.user = user;
            return this.userClient.setGroup(user.id, 'test');
        }
    )
)
.subscribe(
    user => {
        //actions
    },
    error => ...
)

I would like my methods to be turned on one by one, not all at once. how can I do this? forkJoin is the only way out?

CodePudding user response:

Keep the first switchMap, but then return a concat. The concat will sequence the three items you wish for. Concat waits until one is done, then does the next, and so on.

You can find more info on concat on the RxjS Concat docs

this.userClient.getUser(userName)
  .pipe(
    switchMap(
      user => { 
        this.user = user;
        return concat(
            this.userClient.setStatus(this.user.id, 'banned'),
            this.userClient.deleteImg(user.img),
            this.userClient.setGroup(user.id, 'test')
        );
    }
)
)
.subscribe(
  ([user]) => {
    //actions
  },
  error => ...
)

CodePudding user response:

Just use switchMap

this.userClient.getUser(userName)
.pipe(
    switchMap(
        user => { 
            this.user = user;
            return this.userClient.setStatus(this.user.id, 'banned');
        }
    ),
    switchMap(
        user => {
            //set property...
            return this.userClient.deleteImg(user.img);
        }
    ),
    switchMap(
        user => {
            this.user = user;
            return this.userClient.setGroup(user.id, 'test');
        }
    )
)
.subscribe(
    user => {
        //actions
    },
    error => ...
)
  • Related