abelfit
abelfit

Reputation: 15

Angular RxJS Subject subscription and unsubsciption

I have a component to get an update from an API link but API call is not stopping when the component is destroyed. I am using a subject to do so and I unsubscribe from it. my api service is

public getupdate(){
  return this.httpClient.get(this.serverGetUpdate)
}

I have subscribed to this service in my component and want to get and updated every 3 seconds and I do get updates. Here is my code.

export class InprogressComponent implements OnInit, OnDestroy{


subject=new Subject()
  constructor(private apiservice: ApiService) {
    
   }
  
  ngOnInit(): void {
    
    this.getupdate()
  }
  getupdate(){
    this.subject.subscribe(x=>{timer(0,3000).pipe(switchMapTo(this.apiservice.getupdate()),takeWhile(x=>x["data"]=="Something")).subscribe(console.log)})
    this.subject.next()
  }

  

  ngOnDestroy(): void {
    //this.subject.next()
    this.subject.unsubscribe()
  }

}

I am new to RxJS and I do not understand why the API call doesn't stop after unsubscription. I am open to other suggestions too. Thank you

Upvotes: 0

Views: 563

Answers (3)

user15512352
user15512352

Reputation:

Try like this:

export class InprogressComponent implements OnInit, OnDestroy{

 unsubscribe: Subject<void> = new Subject();

  ngOnInit(): void {

    this.getupdate()
  }
  getupdate() {
   this.apiService
      .getupdate()
      .pipe(takeUntil(this.unsubscribe))
      .subscribe(
        data => {
          // do your operation
        },
        error => {
         // error operation
        }
      );
  }



  ngOnDestroy(): void {
     this.unsubscribe.next();
    this.unsubscribe.complete();
  }

}

Upvotes: 0

Donald Duck
Donald Duck

Reputation: 638

Unsubscribe nulls the internal array of subscriptions in the Subject, it does not unsubscribe the subject from it's source

 dataSubscription: Subscription;

  getupdate(){
    this.dataSubscription = this.subject.subscribe(x=>{timer(0,3000).pipe(switchMapTo(this.apiservice.getupdate()),takeWhile(x=>x["data"]=="Something")).subscribe(console.log)})
    this.subject.next()
  }

  

  ngOnDestroy(): void {
    this?.dataSubscription.unsubscribe()
  }

But Brians answer above is a cleaner way to implement your functionality.

Upvotes: 2

Brian Smith
Brian Smith

Reputation: 1656

Try this

export class InprogressComponent implements OnInit, OnDestroy{

 dataSubscription: Subscription = new Subscription();

  ngOnInit(): void {

    this.getupdate()
  }
  getupdate() {
   this.dataSubscription = interval(3000).subscribe(() => {
     console.log('here');
   })
  }



  ngOnDestroy(): void {
    this.dataSubscription.unsubscribe()
  }

}

Upvotes: 2

Related Questions