简体   繁体   English

BehaviorSubject 订阅被调用两次

[英]BehaviorSubject subscription is called twice

I have two component that communicate using a BehaviorSubject .我有两个使用BehaviorSubject通信的组件。 Here's a simple reprodution:这是一个简单的再现:

DashboardComponent:仪表板组件:

this.service.setCheckIsTrue();

Service:服务:

private $checkIsTrue = new BehaviorSubject<any>(null);
public checkIsTrueEvent = this.$checkIsTrue.asObservable();

public setCheckIsTrue(){
    this.$checkIsTrue.next(true);
}

Other component:其他组件:

 this.composerService.checkIsTrueEvent
      .takeWhile(() => this.isAlive)
      .subscribe( res => {
        if(!!res && res){
          console.log("fired"); // <-- called twice
        }
      });

I have others BS that works prefectly fine, so I inspected the code and the function setCheckIsTrue() is called once.我有其他 BS 工作得非常好,所以我检查了代码并调用了一次函数setCheckIsTrue() I could solve this problem using some rxjs operator, but it's not a real solve.我可以使用一些rxjs运算符来解决这个问题,但这不是真正的解决方案。 Anyone has an idea about that happening?任何人都知道发生这种情况吗?

When this happens to me I thrash about a bit until I realize that I've forgotten to unsubscribe in the component's ngOnDestroy().当这种情况发生在我身上时,我会挣扎一下,直到我意识到我忘记在组件的 ngOnDestroy() 中取消订阅。 Give that a try.试一试吧。 :) :)

use condition使用条件

this.composerService.checkIsTrueEvent.takeWhile(() => this.isAlive).subscribe( res => {if('undefined' != typeof res){  
          console.log("fired");// <----called once }
});

You are using BehaviorSubject with initial value null which will notify all subscriber for first time.您正在使用初始值为null BehaviorSubject ,它将第一次通知所有订阅者。 Then you setting the next value by this.$checkIsTrue.next(true);然后你通过this.$checkIsTrue.next(true);设置下一个值which is triggering the next notification.这是触发下一个通知。

If you are not bothered about the last value then you can simply use Subject instead of BehaviorSubject .如果您不担心最后一个值,那么您可以简单地使用Subject而不是BehaviorSubject

private $checkIsTrue = new Subject<any>();

According to my experience most of the time it depends on where you are going to call the function.根据我的经验,大多数时候这取决于您将在哪里调用该函数。 Most of the time it will call twice and generate an error (sometimes) if you are using calling it in the constructor .大多数情况下,如果您在构造函数中调用它,它会调用两次并生成错误(有时)。 You can call it inside ngOnInit() .您可以在ngOnInit() 中调用它。 So it won't generate any errors and won't call the function twice.所以它不会产生任何错误,也不会调用该函数两次。

Also, I tried this one with BehaviorSubject and Subject noting changed.另外,我在BehaviorSubjectSubject注释中尝试了这个。 So you can try the above.所以你可以试试上面的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM