Abort http request on view leave?


#1

Supposing tere is an ajax call when a view loads:

ionViewDidEnter() {
	this.http.get('someurl')
	.subscribe( data => {
                console.log(data)
		//do some stuff here
	})
}

if this is an delay in the response and the user leaves the view (example: go to another page), is it possible to cancel this request? Or do I need to cancel it?

I did some tests, with console.log inside this subscribe and in the ionViewDidLeave event from the component, and when this scenario happens (view is left), the other view is loaded but the previous ajax call is not aborted, and thr console.log(data) outputs the response from the request.


#2

viewDidLeave () {this.http.get('someurl').unsubscribe ();} should do the work.


#3

Thanks @RaulGM
By the way: do you think that the developer needs to worry about this scenario (leave the view before some data has been loaded, and unsubscribe to the Observable)?


#4

These are two points why you should do it:

  • At least to me, sometimes the observable does not work at first, so changing the tab or doing something like that, refreshes the observable and makes it work perfectly.
  • If you change a tab or a page and you don’t unsubscribe to the observable, the observable is going to be working for the entire user-experience. But not only that, if you come back to the page where you have the observable, it will duplicate the observable if you have it on the viewDidEnter () lifecycle, asking for data exponentially more than you’d first wanted.

What I do is to have an observable at viewDidLoad (), unsubscribe it on on viewDidLeave () and subscribe once again on viewDidEnter(). Works like a charm to me.

Happy coding.


#5

Thanks, I’ll do this!

It’s strange that none of the examples I have seen around deal with this issue.