subscribing to observable even when next is not called on BehaviorSubject

北城以北 提交于 2019-12-13 21:08:12

问题


I have a simple scenario:

service.ts:

  private showComposeBoxAction = new BehaviorSubject<boolean>(null);
  showComposeBox = this.showComposeBoxAction.asObservable();


  openComposeBox(event:boolean) {
    console.log("in openComposeBox");
    this.showComposeBoxAction.next(event);
  }

Component.ts:

 constructor(
    private _service: Service,

  ) {

    this.subscriptions.add(
      this._mailingService.showComposeBox.subscribe(event => {
        if (event) {
          this.displayCompose = true;
          console.log("showComposeBox displayCompose", this.displayCompose);
        }
      })
    );

}

component2.ts:

  showComposeBox() {

    if (this.count === 0) {
      this._service.openComposeBox(true);
    }
  }

I have logged a msg within openComposeMsg(). Problem I am facing is that first time I am correctly subscribing to showComposeBox observable but 2nd time when subscribing even when next is not called because msg "in openComposeBox" does not log into console.

Unable to understand behavior of BehaviorSubject. What am I doing wrong?


回答1:


I solved my problem with guidance of JB Nizel and Suren Srapyan. By replacing behavior subject with subject. As observable is subscribed in constructor it triggered and uses current saved value of behavior subject which was set to true previously by other function.

Took reference from This SO But now facing another issue that openComposeBox is called and msg is logged even than observable is not subscribed. I will update answer when I get solution.



来源:https://stackoverflow.com/questions/51318977/subscribing-to-observable-even-when-next-is-not-called-on-behaviorsubject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!