Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rx really work on web (client side)

I have gone through the introduction part at Rx CodePlex page. I have watched the video of the guy with CascadiaJS. I have discovered how the RxJS library is used. I have a question about how is it going to help me with my existing Ajax application and what do I have to change on server side as well as client-side to make the most of RxJS.

Scenario I have a REST service written using ASP.NET Web API. The service currently has one method, it takes an array of coordinates and return another array of coordinates. So the call is very simple, it goes like this.

 $.ajax({
    url: "http://www.myservice.com/service1/",
    type: "POST",
    data: JSON.stringify(params),
    contentType: "application/json;charset=utf-8",
    success: handle_success,
    error: handle_failure,
    OPTIONS: null,
});

Now the above call simply calls a REST service and takes appropriate action on how the results come out.

With Rx, I heard the mantra of "Push" instead of Pull. How are we going to fit "Push" into the sample above ? Am I going to change my REST service to be a Listening TCP Socket which my webpage will stay connected (or make a Keep-Alive connection) and new values will be "Pushed". Or this would just be a service call as above, but the success/error will just be "channeled" through Observable and once the call is finished, the job of that Observable is finished ?

like image 747
fahadash Avatar asked Mar 17 '23 07:03

fahadash


1 Answers

Even without worrying about changing your server to push to the client, RxJs can help you compose your asynchronous actions on the client.

For example, if you model your ajax call as an observable:

// each time you subscribe to service, it will execute the ajax call and send back the result
var service = Rx.Observable.defer(function () {
    return $.ajax({
        url: "http://www.myservice.com/service1/",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json;charset=utf-8"
    });
});

// Now fun with Rx

// just call the service like in your OP example:
service.subscribe(handle_success, handle_failure);

// poll the service every 5 seconds
var pollInterval = Rx.Observable.empty().delay(5000);
service
    .concat(pollInterval)
    .repeat()
    .subscribe(success, failure);

// run the service whenever user clicks Refresh
$('#refresh')
    .onAsObservable('click')
    .flatMap(function () { return service; })
    .subscribe(success, failure);

// same as above, but ignore it when user clicks too fast (e.g. faster than 1 second)
$("#refresh")
    .onAsObservable('click')
    .debounce(1000)
    .flatMap(function () { return service; })
    .subscribe(success, failure);
like image 71
Brandon Avatar answered Mar 23 '23 20:03

Brandon