I subscribed multiple time to an observable but I want to run the callback function only once. is there any rxjs operator to do this?
this.store.select(MsnSelectors.getUserWhoTyping).subscribe(uts => {
if (uts.length > 0) {
let ut = uts.find(x => x.senderUserName === this.receiver.identifier);
console.log(ut)
ut?.isTyping ? this.userTyping = ut : this.userTyping = null;
}
else
this.userTyping = null;
})`
this portion of code is called several times (several subscription), so when the observable emit new value the code inside the subscribe method execute several times.
CodePudding user response:
var store = new Rx.ReplaySubject(1);
store.pipe(skip(1)).subscribe(uts => {
if (uts.length > 0) {
let ut = uts.find(x => x.senderUserName === this.receiver.identifier);
console.log(ut)
ut?.isTyping ? this.userTyping = ut : this.userTyping = null;
}
else
this.userTyping = null;
});
CodePudding user response:
You could perform your logic within a tap
and then use the share
operator to share your subscription so the logic is only executed once:
uts$ = this.store.select(MsnSelectors.getUserWhoTyping).pipe(
tap(uts => /* your logic */ ),
share()
);
subscription1 = this.uts$.subscribe();
subscription2 = this.uts$.subscribe();
subscription3 = this.uts$.subscribe();