如何在BehaviorSubject中更新self时避免无限循环?

时间:2017-12-02 09:51:12

标签: rxjs observable

声明如下:

  public panel$: BehaviorSubject<any> = new BehaviorSubject<any>(false);

像这样使用

  togglepanel() {
    this.panel$.subscribe(
      (x) => {
        if (x) {
          this.panel$.next(false);
        } else {
          this.panel$.next(true);
        }
      });
  }

它创造了一个无休止的循环,试图更新自我。

1 个答案:

答案 0 :(得分:1)

您可以只从panel$ Observable中获取一个(最新)值来更新它:

this.panel$.take(1).subscribe(...)

但是对你的状态建模有点不同,比如:

// const onToggle$ = new Rx.Subject();
var toggle$ = Rx.Observable.fromEvent(document, 'click');

const initialValue = true;
const state$ = toggle$
  .scan(state => !state, initialValue)
  .startWith(initialValue);
      
const htmlSubscription = state$.subscribe(state => {
  document.getElementById('toggle').innerText = 'toggle: ' + state;
});
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
<button id="toggle">loading...</button>

编辑:

此代码的Angular版本为:

  public toggle$ = new Subject();
  public state$ = this.toggle$.scan(state => !state, true)
                        .startWith(true)
                        .subscribe((x) => console.log('x:' + x));


  togglepanel() {
    this.toggle$.next(null);
  }