Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cancel Ajax request on new emmision in rxjs

I am new to reactive programming and having an issue in creating an AJAX navigation side navigation.

<ul>
    <li>change_password</li>
    <li>update_profile</li>
</ul>
<h3> The result </h3>
<div id="theContent"></div>

<script type="text/javascript">
var listClick$ = Rx.Observable.create(function(observer){

            $('li').click(function(){

                let pageName = $(this).html();    
                observer.next(pageName);

            });

        }).startWith('change_password').flatMap(function(pageName){

            return Rx.Observable.fromPromise($.getJSON('http://localhost:3000/settings/'+pageName));        
        });
listClick$.subscribe(function(gottenJson){

$('#theContent').html(gottenJson.page);
}); 
</script>

When i click on change_password or update_profile, an ajax request is made but that of change_password is delayed, so when it is clicked and then update_profile is clicked, update_profile form is displayed but is then replaced by change_password form when it is complete.

How will i be able to cancel the first AJAX request when another list item is clicked?

like image 489
nonybrighto Avatar asked Dec 13 '25 07:12

nonybrighto


1 Answers

You can use switchMap which unsubscribes from the previous stream (your Ajax call) when a new emission is generated.

That being said; because you use a promise Ajax version there is no way to cancel that request. So even though that switchMap provides the hook for cancellation (unsubscribe) the promise will not act upon that.

You can use Rx.Observable.ajax for an Observable version. This call is able to be aborted when you unsubscribe before it has completed. AFAIK it relies on DOM so in a nodejs environment you can use the universal Ajax npm package which replaces the internal xhr with xhr2 from npm when running in a non-DOM env.

like image 121
Mark van Straten Avatar answered Dec 15 '25 12:12

Mark van Straten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!