Rahul
Rahul

Reputation: 2128

Rxjs Subscription triggers more than once

It's very mysterious my subscription is getting triggered more than once - I don't know what was my mistake - I followed the same method on another but it doesn't get triggered more than once

 @Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor() {
    this.getpatientId = this.bindPatientId.asObservable();
  }

  bindPatientId: Subject<number> = new Subject<number>();
  getpatientId: Observable<number>;

  setPatientId(patientId: number) {
    this.bindPatientId.next(patientId);
  }

  bindTabId: Subject<number> = new Subject<number>();
}

Setting new value to the Subject

 toggleProfile(patientId: number) {
    this.commonService.setPatientId(patientId);
    this.route.navigate(['/endrolPatient']);
  }

Listening from another component

ngOnInit() {
    this._common.getpatientId.subscribe(
      (res) => {
        this.patientID = res;
        console.log("console inside observable", this.patientID);
      });
}

In my console when I pass 123 - I'm getting console inside observable 123 but after the first observer rest all the subscriptions get doubled and logging twice in my console - Please help me to fix it

Upvotes: 0

Views: 2871

Answers (2)

Amit Chigadani
Amit Chigadani

Reputation: 29715

That is probably because your component is getting destroyed and created again. So when your component destroys, you have to destroy all the subscriptions. You can do this in ngOnDestroy life cycle method

code:

class MyComponent implements OnInit, OnDestroy {

private sub: Subscription;

ngOnInit() {
    this.sub = this._common.getpatientId.subscribe(
      (res) => {
        this.patientID = res;
        console.log("console inside observable", this.patientID);
      });
}

ngOnDestroy(){
   this.sub.unsubscribe():
}

Upvotes: 5

Ratnabh Kumar Rai
Ratnabh Kumar Rai

Reputation: 584

Use Behaviour Subject whenever you use Subject for everything !, i too faced the problem some time ago but that worked for me !

 bindPatientId: Subject<number> = new BehaviourSubject<number>();
 bindTabId: Subject<number> = new BehaviourSubject<number>();

Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an onnext and you can also use

import { take } from 'rxjs/operators';

and then add

.pipe(
  take(1)

before the subscrbe

Have a look here https://www.learnrxjs.io/operators/filtering/take.html

Hope this may help you !

Upvotes: 0

Related Questions