BehaviorSubject subscriber gets same next() element multiple times

狂风中的少年 提交于 2019-12-25 02:15:36

问题


I'm using a shareData service using BehaviorSubject like the one below. My problem is that every time I call the service's changeMessage method from one component the listener messageSource subscription in any other component is called several times, looks like it received the same message several times. Is this expected behavior? How to prevent it?

The service is a singleton. I do not call changeMessage multiple times

@Injectable()
export class ShareDataService {

    messageSource = new BehaviorSubject(someData);
    currentMessage: Observable = this.messageSource.asObservable();
    changeMessage(message) {
        this.messageSource.next(message);
    }

}

Subscription in component

ngDoCheck() {
    this.shareDataService.currentMessage
        .pipe(takeUntil(this.ngUnsubscribe))
        .subscribe((message) => {
            //Do stuff
        }
    });
}

回答1:


A new subscription is added every time ngDoCheck() is called. Try using first() to only get the value once and then automatically unsubscribe.

ngDoCheck() {
    this.shareDataService.currentMessage
        .pipe(first())
        .subscribe((message) => {
            // Do stuff
        }
    });
}

The next time ngDoCheck is triggered, it adds another one-time subscription.


If your only intention of the subscription is to get the current value on change detection, you can also add a simple get() function to your ShareDataService to just return its current value.

get() {
    return this.messageSource.getValue();
}



回答2:


Can you please try calling the unsubscribe in your ngOnDestroy() lifecycle hook

ngOnDestroy() {
    this.shareDataService.currentMessage.unsubscribe();
}

Hope this helps!



来源:https://stackoverflow.com/questions/51478183/behaviorsubject-subscriber-gets-same-next-element-multiple-times

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