【问题标题】:Update spesific element in behaviorsubject, or only subscribe once更新behaviorsubject中的特定元素,或者只订阅一次
【发布时间】:2019-04-12 00:14:51
【问题描述】:

我有一个BehaviorSubject,它每 5 秒从我的其他文件中获得持续更新。

但是,有时我不能等待 5 秒才能发生新事件,所以我正在寻找一种方法来仅更新 Behaviorsubject 的单个元素。

我创建了以下内容来处理单个元素:

 updateSingleTimer(timer,time,secs = false) {
    this.timers$.pipe(takeUntil(this._destroyed$)).subscribe((data:any) => {
      var newdata = data;
      newdata[timer] = time;
      this.updateTimers(newdata);
    });
  }

当然,这将创建一个无限循环,因为一旦调用updateTimers 函数,就会更新计时器。

所以,我只需要在updateSingleTimer 函数中获取计时器数据一次,而不是订阅它。

问:如何更改上面的代码,使其只能从this.timers$ 获得一次结果?

问:另外,是否有可能以比我目前所做的更简单的方式更新单个元素?

完整代码:

  _timers = new BehaviorSubject<any>(null);
  private timersChangeSet = new Subject<any>();
  constructor(private http: HttpClient, private router: Router) {
    this.timersChangeSet.subscribe(val => this._timers.next(val))
}

  timers$ = this._timers.asObservable();

updateTimers(object) {
    this.timersChangeSet.next(object);
  }


  updateSingleTimer(timer,time,secs = false) {

// the code will result in infinity loop, of course. but how would i only get the value once?
    this.timers$.pipe(takeUntil(this._destroyed$)).subscribe((data:any) => {
      var newdata = data;
      newdata[timer] = time;
      this.updateTimers(newdata);
    });
  }

【问题讨论】:

    标签: javascript angular rxjs behaviorsubject


    【解决方案1】:

    只需1个

    this.timers$.pipe(take(1), takeUntil(this._destroyed$))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多