Is there a way to re-subscribe after unsubscribing RxJS?

Viewed 1576

Here is a sample code that subscribes to Http request and cancels it upon mouse click on the page. I would like to resubscribe if I perform click once again.

How can I toggle subscription? FIDDLE

export class AboutComponent implements OnInit {
constructor(private http:HttpClient){
}

flag=true;
documentclick = fromEvent(document, 'click');

 private data = {
    name:  'Samurai',
    profession:  'Developer'
  };
  ngOnInit(){

    let subscription:Subscription = this.getGoogle()   )
    .subscribe((res)=> {
     console.log(res);
   })

    this.documentclick.subscribe( e=>{
      if(this.flag){
        subscription.unsubscribe();
      }
      else{
        subscription = this.getGoogle().subscribe((res)=> {
          console.log(res);
        });
      }
      this.flag != this.flag;

    });
  }

getGoogle(): Observable<any> {
    return   this.http.get( 'https://jsonplaceholder.typicode.com/todos/1').pipe ( delay( 2000 ) )
  }

}

With the above code I am able to cancel the request if I click the page within 2 seconds. But I am not able to subscribe again on clicking again.

Also, it would be great if someone could tell me if I am really cancelling the http request with unsubscribe()? Or is it just an illusion? Will the request hit the server if I unsubscribe withing 2 seconds?

1 Answers

Your code has a logic error, just a typo I think.

this.flag != this.flag;

You probably meant

this.flag = !this.flag;

By the way (unrelated to your issue) your method of getting document clicks is a non-angular way and you may run into issues with the page not updating. Consider using a HostListener instead:

@HostListener('document:click', ['$event'])
clicked(event) {
    ..
}

Unsubscribing from the HTTP request should cancel the request. However, you have no guaranteed way of knowing if the request actually went through to the server, or not - the server may have already replied by the time you unsubscribed.

Here's a cleaned-up stackblitz: https://stackblitz.com/edit/angular-fzlzcf

Related