如何根据条件以角度链接可观察对象

问题描述

我有一个订阅中的订阅,并且我想链接它,但是我不确定应该如何继续,因为if块内部已订阅了实习生。

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();
  }
});

我希望以某种方式链接它,使其只能订阅一次。 我当时认为将它放在某个可以顺序运行的数组中会很好吗?

解决方法

switchMap可以解决问题。沿着这些路线……

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();
  }
});
,

您可以使用iif运算符:

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

如果您有两个以上的选项,则可以在switchMap中手动使用if语句。

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...