Marek Panti
Marek Panti

Reputation: 126

How to chain observables in angular, based on condition

I have a subscribe in subscribe and I would like to chain it, but I am not sure how should I continue, as intern subscribed is inside if block.

authenticationService.isLoggedIn$.subscribe(isLoggedIn => {
  this.isLoggedIn = isLoggedIn;
  if (isLoggedIn) {
    socketService.initSocket();
    authenticationService.refresh().subscribe(time => {
      this.timeOut = time.expirationTime;
      this.setTimeout(this.timeOut);
    });
  } else {
    clearTimeout(this.userActivity);
    socketService.destroySocket();
  }
});

I would love to chain it somehow to be able to subscribe on it only once. I was thinking it would be good to put it inside some array which would sequentially run it?

Upvotes: 1

Views: 820

Answers (2)

code-gorilla
code-gorilla

Reputation: 2438

You can use the iif operator:

let subscribeToFirst;
const firstOrSecond = iif(
  () => subscribeToFirst,
  of('first'),
  of('second'),
);
 
subscribeToFirst = true;
firstOrSecond.subscribe(value => console.log(value));

In case you have more than 2 options you can use manually construct if statements in switchMap.

myObs$
  .pipe(
    switchMap(val => {
      if(a) { return obsA$ }
      else if(b) { return obsB$ }
      else { return obsElse$ }
    })
  ).subscribe();

Upvotes: 1

mbojko
mbojko

Reputation: 14689

A switchMap could do the trick. Sth along those lines:

return authenticationService.isLoggedIn$.pipe(
  tap(isLoggedIn => this.isLoggedIn = isLoggedIn),
  switchMap(isLoggedIn => isLoggedIn ? authenticationService.refresh() : of(null)))
.subscribe(time => {
  if (time) {
    this.timeOut = time.expirationTime;
    this.setTimeout(this.timeOut);
  } else {
    clearTimeout(this.userActivity);
    socketService.destroySocket();
  }
});

Upvotes: 3

Related Questions