Matthew Podwysocki's Blog

Architect, Develop, Inspire...

  • Introduction to the Reactive Extensions for JavaScript – Conditionals

    After spending the past couple of posts talking about how we integrate and why, let’s get back to the basic operators of the Reactive Extensions for JavaScript.  This time, we’ll cover conditional logic that we can do with RxJS (which also applies to Rx.NET as well).  With traditional LINQ, we have the Where operator which allows us to filter operations, but it doesn’t allow us to do one operation or another easily.  Instead, the Reactive Extensions team has included two operators, If and Case which allow us some flexibility on how we want to execute conditional logic.

    Before we get started, let’s get caught up to where we are today:

    Conditional Branching with Observable.If

    The first conditional operator we’ll cover is the Observable.If function.  This function acts as a normal if statement would in that it allows us to specify a conditional function and then have a branch for the “then” logic and another branch for the “else” logic.  The signature of the function is below:

    // condition  : () -> bool
    // thenSource : Observable
    // elseSource : Observable
    
    // returns : Observable
    
    Rx.Observable.If(
        condition,
        thenSource,
        elseSource);

    For example, I could determine whether I want to use the cached value of an observable or start a fresh request to get some data based upon some setting.

    var cachedObservable = new Rx.Subject();
    
    ...
    
    Rx.Observable.If(
        function() { return shouldCache; },
        cachedObservable
        Rx.Observable.Defer(
            function() {
                return $.getJSONAsObservable("someurl");
            })
        );

    You’ll notice that I deferred the getJSONAsObservable and there’s a very good reason for that.  Such AJAX calls as this one are hot observables which mean that they fire immediately instead of waiting for the Subscribe call being made.  We’ll get into the whole hot versus cold observables in another post.

    So, you might be thinking, what’s the difference then between this and if I had written it the old fashioned way using an if statement?

    var cachedObservable = new Rx.Subject();
    
    ...
    
    if (shouldCache) {
        return cachedObservable;
    }
    else {
        return Rx.Observable.Defer(
            function() {
                return $.getJSONAsObservable("someurl");
            });
    }

    Well, the difference between the two is that the Rx.Observable.If function will evaluate the condition on subscription, whereas the if statement will evaluate eagerly for example on a hot observable.  The if statement is nice, but what if we have more than just a simple binary case?

    Conditional Branching with Observable.Case

    Another mechanism we have for branching logic is be being able to handle a switch statement.  What we want to give is the ability to write your traditional switch statement, but have it lazily execute just as we have the If function above.  We can take the following as an example where based upon n, return the appropriate Observable value.

    switch(n)
    {
        case 1:
            return Rx.Observable.Return(1);
        case 2:
            return Rx.Observable.Return(2);
        default:
            return Rx.Observable.Return(3);
    }        

    In order to make this happen, we need to use the Rx.Observable.Case function which allows us to specify a condition, such as checking for the value of n, a hash object which contains key/value pairs with the key and their Observable value, and finally an optional default case.

    // selector : () -> Key
    // sources  : Dictionary<Key, Observable>
    // defaultSource : Observable
    
    // returns : Observable
    
    Rx.Observable.Case(
        selector,
        sources,
        defaultSource);

    In the case of our above switch statement, we’ll first want to create the hash of our sources.  Basically, the property name is the key and its value is the value of the key/value pair.

    var sources = {
        1 : Rx.Observable.Return(1),
        2 : Rx.Observable.Return(2)
    };

    Now that we have the sources, let’s finish off the implementation.  First, for our selector, we’ll need to provide a function which takes no parameters and returns our desired key.  Next, we’ll provide the sources from above, and finally we’ll provide a default case if no others match.

    var cased = Rx.Observable.Case(
        function() { return n; },
        sources,
        Rx.Observable.Return(3));

    So, in the case of n being 1, then the first source will be selected, and so on for those along the line.  If n does not match either 1 nor 2, the defaultSource will be selected.  Let’s run through a quick example where we check if the detected language is a language we support, either French or Spanish, and if we do, then we translate.  Else, we will go ahead and throw an exception via the Rx.Observable.Throw function as part of the workflow to say that the given language isn’t supported.

    // The variables could be something like:
    // var detected = "fr";
    // var text = "Nous allons traduire un texte";
    
    var sources = {
        es : Rx.Observable.Defer(
                function() { return translateFromSpanish(text);
             }),
        fr : Rx.Observable.Defer(
                function() { return translateFromFrench(text);
             })
    };
    
    Rx.Observable.Case(
            function() { return detected; },
            sources,
            Rx.Observable.Throw("Not supported!"))
        .Subscribe(
            function(data) {
                alert(data);
            },
            function(err) {
                alert("An error occurred: " + err);
            });
    

    And there you have it, you now have two ways of dealing with lazy conditional logic within your observable workflow.

    Back to .NET

    Even though my examples here are primarily in JavaScript, we have the exact same functionality in the Reactive Extensions for .NET and Silverlight.  For example, the If function is implemented as well with the signature as follows:

    public static IObservable<TResult> If<TResult>(
        Func<bool> condition,
        IObservable<TResult> thenSource,
        IObservable<TResult> elseSource
    )

    And a simple example of using this, such as an even/odd scenario:

    Observable.If<string>(
        () => n % 2 == 0,
        Observable.Return("even"),
        Observable.Return("odd"));

    Just as well, we can use the Case statement, which has the following signature:

    public static IObservable<TResult> Case<TValue, TResult>(
        Func<TValue> selector,
        IDictionary<TValue, IObservable<TResult>> sources,
        IObservable<TResult> defaultSource
    )

    And then we could walk through a simple example of creating our cases and then call the case with our variable n which could be either our 1, 2 or anything else.

    var sources = new Dictionary<int, IObservable<int>>
    {
        { 1, Observable.Return(1) },
        { 2, Observable.Return(2) }
    };
    
    var cased = Observable.Case<int>(
        () => n,
        sources,
        Observable.Return(3));

    As with most examples I give on this blog, most of the core operators work nicely when going back and forth from RxJS to RxNET.

    Conclusion

    Dealing with asynchronous programming has been in the forefront of many minds in the JavaScript community.  At JSConf, there were several examples of frameworks trying to get around the idea of callbacks and instead lean more towards composition.  By utilizing the Reactive Extensions for JavaScript, we’re able to compose together asynchronous and event-based operations together and transform the results in interesting ways. 

    When we start creating more advanced workflows through the Reactive Extensions, we need powerful ways of expressing such concepts as conditional logic outside of the Where function we’re already accustomed to.  With the If and Case functions, we have two powerful pieces at our disposal to make those more complicated pieces a reality.

    So with that, download it, and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – MooTools Integration

    In the previous post, I covered a bit about how we’ve integrated the Dojo Toolkit into the Reactive Extensions for JavaScript (RxJS) where we can leverage Dojo’s eventing and AJAX programming model.  Following onto that post, I wanted to move onto a different framework and show how we integrated it into RxJS.  This time, it’s MooTools up to the plate.

    Now the question comes, why then if the given framework works as well as it does, why would we care to integrate it into RxJS?  What does it buy us?  What if we want to combine two mouse moves together, one offset from the other so that we get a delta from the previous?  Or how about throttling the values coming from our events, either the first value only or a delay between each value?  Between all the callbacks, setTimeouts and the global state that you need to track, it becomes very hand to manage.  That’s the reason why we’ve created this layer where we can go seamlessly from MooTools and other JavaScript frameworks to RxJS.  We can either hop out of the world of our framework and into RxJS, or integrate it underneath the covers to manage the composable nature of your framework.  Both are great options…

    Before we get started, let’s get caught up to where we are today:

    Diving Into MooTools Events

    Once again the first part of our journey is to cover the eventing model of MooTools.  MooTools has the ability through any number of classes to be able to listen to events.  We’ll start with the Element class method addEvent, which attaches an event listener to a given DOM element. 

    someElement.addEvent(
        type, 
        fn);

    Each parameter is described below:

    • type (string) – the name of the event to monitor such as click, mousemove, etc.
    • fn (function) – the callback function to execute when the event is fired.

    The fn callback as noted above gives us a Event which has any number of properties including page and client position, keys used, the target and related targets as well as some methods to stop propagation. 

    Conversely to our addEvent, we can remove our handler from the Element by using the removeEvent method.

    someElement.removeEvent(
        type, 
        fn);

    Each parameter is described below:

    • type (string) – the name of the event to remove
    • fn (function) – the callback function to remove

    We can then listen to events in MooTools such as a keyup event on a given input element.

    $("someInput").addEvent("keyup", 
        function(event) {
            $("whatkey").set("html", key);
        });

    We can wrap these events by using the Rx.Observable.Create function which hands us an observer to use and then we return a disposable which allows us to remove our listener.  Inside the Create function, we’ll create a handler which takes the event object from MooTools and passes it to the observer.OnNext.  After we’ve defined the handler, we call addEvent on our MooTools Element with the event type and we’ll pass in the handler as the method to invoke.  Finally, we return a function which is invoked when we call Dispose on our subscription.  Below is a wrapped version called Rx.Observable.FromMooToolsEvent.

    Rx.Observable.FromMooToolsEvent = function(obj, eventType) {
        return observable.Create(function(observer) {
        
            // Create handler for OnNext
            var handler = function(eventObject) {
                observer.OnNext(eventObject);
            };
            
            // Subscribe to event
            obj.addEvent(eventType, handler);
            
            // Return function used to remove event handler
            return function() {
                obj.removeEvent(eventType, handler);
            };
        });
    };

    What this allows is for us to use a MooTools element to attach an event much like the following:

    var element = $("someElement");
    
    Rx.Observable.FromMooToolsEvent(element, "mousemove")
        .Where(
            function(event) {
                return event.client.x === event.client.y;
            })
        .Subscribe(
            function(event) {
                $("mousePosX").set("html", event.client.x);
            });

    That’s all well and good, but I think it’s better to live and breathe within MooTools itself.  In order to do so, we need to extend a few objects that expose adding and removing event handlers, such as Element, Elements, Window, Document as well as any other class which inherits from the Event class.  To do that, we’ll use the Class method implement in which we pass in properties which alters the base class so that we can modify existing classes.  For example, I can extend the Element and all other classes mentioned above by doing the following:

    var fromMooToolsEvent = function(type) {
        return fromMooToolsEvent(this, type);
    }
    
    Window.implement({
        addEventAsObservable : fromMooToolsEvent
    });
    
    Document.implement({
        addEventAsObservable : fromMooToolsEvent
    });
    
    Element.implement({
        addEventAsObservable : fromMooToolsEvent
    });
    
    Elements.implement({
        addEventAsObservable : fromMooToolsEvent
    });    
    
    Events.implement({
        addEventAsObservable : fromMooToolsEvent
    });  

    By doing this, we can take the above example of hooking a mouse move listener to report the x position relative to the viewport when both the x and y values are the same:

    $("someElement").addEventAsObservable("mousemove")
        .Where(
            function(event) {
                return event.client.x === event.client.y;
            })
        .Subscribe(
            function(event) {
                $("mousePosX").set("html", event.client.x);
            });

    Now that we have the basics down here, what about the AJAX APIs?

    Diving into the Request

    Another area where the Reactive Extensions for JavaScript can integrate well is with AJAX APIs.  MooTools exposes three such classes in the Core library, Request, Request.HTML and Request.JSON.  Each of those do as you suspect with one handling general requests such as text, whereas the HTML and JSON classes handle their respective data types.  But the one I’m going to focus on is in the More MooTools library called Request.JSONP, which allows me to make cross-domain JSON calls.

    new Request.JSONP(options);

    The documentation for options is as follows:

    • url - (url) the url to get the JSON data
    • callbackKey - (string) the key in the url that the server uses to wrap the JSON results. So, for example, if you used callbackKey: 'callback' then the server is expecting something like http://..../?q=search+term&callback=myFunction; defaults to "callback". This must be defined correctly.
    • data - (object) additional key/value data to append to the url
    • retries - (integer; defaults to zero) if this value is a positive integer, the JSONP request will abort after the duration specified in the timeout option and fire again until the number of retries has been exhausted.
    • timeout - (integer; defaults to zero) the duration to wait before aborting a request or retrying.
    • injectScript - (mixed; defaults to document head) where to inject the script elements used for the calls
    • log - (boolean) if true, sends logging messages to Log (to console if it's defined). Defaults to false.

    For example, should we want to search on Twitter once again, we can pass in our URL, the data for the query string, the callback and a function used for the callback.  We can then create the Request.JSONP instance with our options and send our request.  

    var options = {
        url: 'http://search.twitter.com/search.json',
        data: { rpp: "100", q: "4sq.com" }
        callbackKey: "callback" 
        onComplete: 
            function(data) {
                $("results").set("html", data.results[0].text);
            }
    };
    var req = new Request.JSONP(options);
    req.send();

    We could also cancel our request as well should we need to by using the cancel function.  Once again, the issue arises of composability as well as error handling.  How could we integrate with key up events and throttle our request?  Sooner or later when we start composing things together via callbacks, our code could walk right off the screen.  Instead, RxJS could allow us some flexibility to compose events and AJAX calls together.  To make this happen, we can wrap the API once again like we did with Dojo and jQuery, but this time we’ll take a different approach.

    As before, we’ll create an AsyncSubject, which is used for asynchronous communication that happens once and then caches the value.  Next, we need to handle both the success and error conditions by adding the functions load and error respectively to the options object.  The load function simply passes the data where we call the subject’s OnNext with the data and then mark it as complete with the OnCompleted call.  The error function simply is given an error object so that we can see what went wrong and act accordingly.  Now what’s different between the two approaches is that we’re supporting a cancel option.  If we should call Dispose on our subscription before the request is complete, we want to have the ability to cancel our request.  To make this happen we’ll create a RefCountDisposable which allows us to cancel our request should we need to.  And finally we’ll return a CompositeDisposable which takes the Disposable from the AsyncSubject and from the cancel together so that if one ends before the other, then we can continue with the second.

    observable.MooToolsJSONPRequest = function(options) {
    
        var subject = new root.AsyncSubject();
        var request = null;
        
        try {
            options.onSuccess = function(html) {
                subject.OnNext(html);
                subject.OnCompleted();
            };
        
            options.onFailure = function(xhr) {
                subject.OnError({ kind: "failure", xhr: xhr });
            };
        
            options.onException = function(headerName, value) {
                subject.OnError({ kind: "exception", headerName: headerName, value: value });
            };
            
            request = new Request.JSONP(options);
            request.send();
        }
        catch(err) {
            subject.OnError(err);
        }
        
        var refCount = new root.RefCountDisposable(root.Disposable.Create(function() {
            if(request) {
                request.cancel();
            }
        }));
        
        return observable.CreateWithDisposable(function(subscriber) {
            return new root.CompositeDisposable(subject.Subscribe(subscriber), refCount.GetDisposable());
        });    
    }    

    We can also extend the Request.JSONP class (and thanks for the assistance from Sebastian Markbåge) by using the implement function once again.  We’ll create a toObservable function to implement this same functionality.  There is a difference though that the options are private to the class.  So, we can either use the setOptions function to set the options or since the Request.JSONP class inherits from the Events class, we can call addEvents directly to add properties for success, failure and exception cases.

    Request.JSONP.implement({
       
        toObservable: function () {
            var subject = new root.AsyncSubject();
            var request = this;
            try {
                
                request.addEvents({
        
                    success: function(data) {
                        subject.OnNext(data);
                        subject.OnCompleted();
                    },
        
                    failure: function(xhr) {
                        subject.OnError({ kind: "failure", xhr: xhr });
                    },
        
                    exception: function(headerName, value) {
                        subject.OnError({ kind: "exception", headerName: headerName, value: value });
                    }
        
                });
                
                request.send();
            }
            catch (err) {
                subject.OnError(err);
            }
        
            var refCount = new root.RefCountDisposable(root.Disposable.Create(function () {
                request.cancel();
            }));
        
            return observable.CreateWithDisposable(function (subscriber) {
                return new root.CompositeDisposable(subject.Subscribe(subscriber), refCount.GetDisposable());
            });
        }        
    }); 

    Once we’ve implemented this, we’re able to redo example where we query Twitter for those who are posting to FourSquare and has geolocation turned on and get the maximum user ID and then print their text.

    window.addEvent("domready", function() {
        var options = {
            url: "http://search.twitter.com/search.json",
            data: { rpp : "100", q : "4sq.com" },
            callbackKey: "callback"
        };
    
        new Request.JSONP(options)
            .toObservable()
            .SelectMany(
                function(data) {
                    return Rx.Observable.FromArray(data.results);
                })
            .Where(
                function(result) {
                    return result.geo != null;
                })
            .Max(
                function(result) {
                    return result.from_user_id;
                })
            .Subscribe(
                function(result) {
                    alert(result.text);
                },
                function(error) {
                    alert("An error!" + error.description);
                });
    });

    You can find the complete MooTools integration here and will be available in the next release of RxJS.

    Instead of this example where we go from MooTools to RxJS, we could also extend a number of classes to create an API totally in MooTools with RxJS underneath the covers.  With this, we could implement behavior similar to that of Towel.js, an extension to MooTools for reactive programming.

    Conclusion

    Dealing with asynchronous programming has been in the forefront of many minds in the JavaScript community.  At JSConf, there were several examples of frameworks trying to get around the idea of callbacks and instead lean more towards composition.  By utilizing the Reactive Extensions for JavaScript, we’re able to compose together asynchronous and event-based operations together and transform the results in interesting ways. 

    One important aspect of the Reactive Extensions for JavaScript is how well we play with other frameworks.  By giving out of the box extensions points, this allows for you to still use your framework of choice along with the Reactive Extensions to take care of the event-based and asynchronous behavior.

    So with that, download it, and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – Wrapping the Dojo API

    Recently in some of the comments I’ve received (keep them coming BTW), I get questions about taking existing APIs and moving them towards using the Reactive Extensions for JavaScript (RxJS).  How can we get away from constant callback hell and move towards composable asynchronous and event-based blocks instead?  In this post, I’m going to walk through how we wrapped the Dojo Toolkit APIs to provide both event handling and AJAX functionality.

    Before we get started, let’s get caught up to where we are today:

    Wrapping Dojo Events

    The first part of connecting the Dojo Toolkit to RxJS is by wrapping the eventing model.  The Dojo Toolkit has the dojo.connect function which allows us to listen in on the execution of either DOM events or even function calls with a listener to be invoked when it is fired.  Conversely, if we wish to stop listening, we can call dojo.disconnect to remove the listener.  The connect method is as follows:

    dojo.connect(
        obj, 
        event, 
        context, 
        method, 
        dontFix);

    Each parameter is described below:

    • obj – the source object for the event function
    • event – the name of the event, such as “click”
    • context – the object that the listener will receive as “this”
    • method – a listener function to invoke when the event is fired
    • dontFit – prevent the delegation of this connection to the DOM event manager

    And the connect function returns a handle for which we can use to disconnect.  The disconnect function takes this handle for us to stop listening to the event.

    dojo.disconnect(handle);

    We can wrap these events by using the Rx.Observable.Create function which hands us an observer to use and then we return a disposable which allows us to disconnect our listener.  Inside the Create function, we’ll create a handler which takes the event object from Dojo and passes it to the observer.OnNext.  After we’ve defined the handler, we call connect with the parameters and we’ll pass in the handler as the method to invoke.  That function returns to us a handle which we can then use to disconnect the listener.  Finally, we return a function which is invoked when we call Dispose on our subscription.  Below is a wrapped version called Rx.Observable.FromDojoEvent.

    var fromDojoEvent = Rx.Observable.FromDojoEvent = 
        function(obj, event, context, dontFix) {
        
        return Rx.Observable.Create(function(observer) {
       
            // Handle on next calls
            var handler = function(eventObject) {
                observer.OnNext(eventObject);
            };
           
            // Connect and get handle for disconnecting
            var handle = dojo.connect(obj, event, context, handler, dontFix);
           
            // Return disposable used to disconnect
            return function() {
                dojo.disconnect(handle);
            };
        });
    };

    If we want to make it look and feel more like it belongs in Dojo itself, we could also alias it as dojo.connectAsObservable as we so wish.  This part isn’t actually in the codebase just yet, but if the feedback is positive, then it can be.

    dojo.connectAsObservable = function(obj, event, context, dontFix) {
        return fromDojoEvent(obj, event, context, dontFix);
    };

    Below is an example to connect to a given button and then listen for one out of every four clicks.

    var obj = dojo.byId("someButton");
    
    var sub1 = Rx.Observable.FromDojoEvent(obj, "click")
        .Sample(4)
        .Subscribe(function() { alert("Fourth click!"); });
    
    // Or
    
    var sub2 = dojo.connectAsObservable(obj, "click")
        .Sample(4)
        .Subscribe(function() { alert("Fourth click!"); });

    Wrapping Callback Scenarios

    Another part of an API we can wrap is around asynchronous behavior with callbacks, especially for such things as AJAX calls and effects.  For this part, we’re going to cover taking the dojo.io.script.get function and creating an observable from it.  The dojo.io.script.get function is an alternate IO mechanism to dojo.xhrGet that has the capability of doing cross-site data access by dynamically inserting a <script> tag into your web page.  This mechanism also supports JSONP for named callback scenarios.  Let’s look at the signature for the get function.

    dojo.io.script.get = function(
        options);

    The options takes the following properties:

    • url – The URL to request data
    • callbackParamName – The callback string used for JSONP
    • checkString – A type of check to ensure the script has been loaded. Not used in
    • preventCache – True to apply a unique parameter to prevent the browser from caching
    • content – A JavaScript object of key/value pairs for parameter names and values

    For example, we can create the options much like the following:

    var jsonpArgs = {
        url: "http://search.twitter.com/search.json",
        callbackParamName: "callback",
        content: { rpp: "100", q: "4sq.com" } };

    In order to use the get function, we also have to ensure that we’ve reference the dojo.io.script module such as the following:

    dojo.require("dojo.io.script");   

    Now we can get down to how we’d wrap the functionality.  First, we’ll create an AsyncSubject, which is used for asynchronous communication that happens once and then caches the value.  Next, we need to handle both the success and error conditions by adding the functions load and error respectively to the options object.  The load function simply passes the data where we call the subject’s OnNext with the data and then mark it as complete with the OnCompleted call.  The error function simply is given an error object so that we can see what went wrong and act accordingly.  We can then call the get function with our options and then finally return our AsyncSubject.

    Rx.Observable.FromDojoScriptGet = function(options) {
        // Create subject
        var subject = new Rx.AsyncSubject();
        
        // Handle success
        options.load = function(data) {
            subject.OnNext(data);
            subject.OnCompleted();
        };
        
        // Handle failure
        options.error = function(error) {
            subject.Error(error);
        };
        try {
            // Load the script
            dojo.io.script.get(newOptions);
        }
        catch (err) {
            subject.OnError(error);
        }
        
        return subject;        
    }; 

    This pattern applies to any callback scenario where we have one value to yield and then we want to cache it.  And now we can query Twitter with the Reactive Extensions with Dojo underneath the covers.  For example, we could query Twitter for those who are posting to FourSquare and has geolocation turned on and get the maximum user ID and then print their text.

    dojo.addOnLoad(function() {
    
        var jsonpArgs = {
            url: "http://search.twitter.com/search.json",
            callbackParamName: "callback",
            content: { rpp: "100", q: "4sq.com" } };
    
        Rx.Observable.FromDojoScriptGet(jsonpArgs)
            .SelectMany(
                function(data) {
                    return Rx.Observable.FromArray(data.results);
                })
            .Where(
                function(result) {
                    return result.geo != null;
                })
            .Max(
                function(result) {
                    return result.from_user_id;
                })
            .Subscribe(
                function(result) {
                    alert(result.text);
                },
                function(error) {
                    alert("An error!" + error.description);
                });
    });

    These two patterns for wrapping events and asynchronous operations doesn’t stop at Dojo, but also applies to the other frameworks out there including YUI3, Prototype, ExtJS, jQuery and so forth.  For the AJAX calls, MooTools is different and we’ll get into that in the next post.

    Conclusion

     

    Dealing with asynchronous programming has been in the forefront of many minds in the JavaScript community.  At JSConf, there were several examples of frameworks trying to get around the idea of callbacks and instead lean more towards composition.  By utilizing the Reactive Extensions for JavaScript, we’re able to compose together asynchronous and event-based operations together and transform the results in interesting ways. 

    One important aspect of the Reactive Extensions for JavaScript is how well we play with other frameworks.  By giving out of the box extensions points, this allows for you to still use your framework of choice along with the Reactive Extensions to take care of the event-based and asynchronous behavior.

    So with that, download it, and give the team feedback!

    Read more...

  • Talking Reactive Extensions

    There has been a lot of movement around the Reactive Extensions lately and I thought I’d round them up for you in an easy to find location.  Between the new release and various interviews, there’s a bit to cover.

    New Release

    Last Friday there was a release of the Reactive Extensions for both .NET and JavaScript for which the release notes can be found here.  On the .NET side of the house, the biggest addition is the addition of IQbservable, which is short of IQueryableObservable.  Just as IObservable is the mathematical dual of IEnumerable, IQbservable is the dual of IQueryable.  Bart de Smet, of the Cloud Programmability Team, explains it in full detail in his Channel 9 white boarding sessions here.

    On the JavaScript side of things, there were a few more items of note.  This includes some additional bindings for Dojo, Ext JS, jQuery, MooTools, Prototype and YUI3.  We ship the debug versions of these integrations so that you get an idea of how we did it, but just as well, how you could add more integration points yourself.  One new integration point that I’m very excited about is the Raphael bindings.  If you’re not familiar with Raphael, it is a JavaScript library for simplifying interaction with vector graphics on the web.  I hope to cover more of that shortly on what it is and how we did it.  Lastly, there have been quite a few new operators that have been added in the form of Case, DoWhile, If, For, Let and While.  Each of these will be covered as well coming up.  But by no means are we even close to being done!

    JSConf

    A few weeks ago, I, along with Jeffrey Van Gogh, attended the preeminent JavaScript conference, JSConf here in Washington, DC.  There, we got to meet some of the best and brightest in the JavaScript community and share ideas, and in our case around event-based and asynchronous patterns in JavaScript.  What was interesting was the talk breakdown between server side and client side JavaScript seemed about a 50-50 split, with a lot of focus on Node.js.  Noticing this trend, Jeffrey presented in the B Track on the Reactive Extensions where he announced our bindings for Node.jsRey Bango caught up with us on Sunday to talk to us about the Reactive Extensions for JavaScript which you can view here.  Also, there was a great wrap-up of JSConf on Herding Code with the organizer, Chris Williams, Rey Bango and myself on Herding Code you might want to check out.

    Overall, it was a great event and I’d highly recommend attending the upcoming JSConf.EU if you get the chance (although I hear it did sell out). 

    Interviews and More

    As if you hadn’t heard enough already, we’ve had a few interviews on various podcasts where we dig into the Reactive Extensions for .NET and JavaScript. 

    With that, download the Reactive Extensions and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – The Final Countdown Timer

    In the previous couple of posts, I’ve talked about asynchronous method chaining and creating custom schedulers so I can repeatedly hit a data source for its data, transform it and then display the results.  Instead of just setting a custom interval between the results and querying the system, so this time, I want to stick a timer where I can monitor the time between queries. 

    Before we get started, let’s get caught up to where we are today:

    Creating Countdowns with GenerateWithTime

    In previous posts, the goal was to repeatedly query a system with a given interval so that we could see what is going on in the world of Twitter.  The goal of this post is to take this idea a step further to have a timer display how long we have until the system refreshes itself, and when the timer is exhausted, we requery and reset the timer.  To do this, we’ll need to make use of the GenerateWithTime function.  This function takes five parameters:

    1. The initial state of the timer
    2. The condition of the timer of whether to continue
    3. The result selector which takes the state and you return what you want from it
    4. The time selector which says how much time you want between calls
    5. The iterate function which takes the state and increments it

    Below is the signature of the GenerateWithTime function:

    // initialState : State
    // condition : State -> bool
    // resultSelector : State -> Result
    // timeSelector : State -> int
    // iterate : State -> State
    
    Rx.Observable.GenerateWithTime = function(
        initialState, 
        condition, 
        resultSelector, 
        timeSelector, 
        iterate);

    Now that we have some clue on what it’s expecting, let’s go ahead and put it to some good use.  What we’re going to do is create a timer that counts down from 90 seconds while setting the countdown element to the current value at each second interval.  You’ll notice the initial state is set to 90, the condition is while the state is greater than or equal to zero, our time selector is one second and our iterate decrements the state by one.

    function countdownUI() {
        return Rx.Observable.GenerateWithTime(
            90,
            function(x) { return x >= 0; },
            function(x) { return x; },
            function(x) { return 1000; },
            function(x) { return x - 1; })
            .Do(function(x) { $("#countdown").html(x); });
    }

    Our ultimate goal is to have something happen at the front end, such as query Twitter, count down from 90 seconds and then query again.  To facilitate that need, I’ll create the updateUI function which queries Twitter and pulls the first record that matches and then displays the result in our content area.

    function updateUI() {
        var url = "http://search.twitter.com/search.json?q=4sq.com&rpp=1";
        return $.getJSONAsObservable(url)
            .Select(function(d) { return d.data.results[0].text; })
            .Do(
                function(result) {
                    $("#content").html(result);
                });
    }

    Once we’ve defined both our countdownUI and updateUI functions, let’s compose them together in such a way that it fires the updateUI, counts down to zero, then rinse and repeat.  To make use of that, we must first defer the Twitter search until we’ve subscribed which allows us to repeatedly call it and have it requery.  The Defer function is a static function which takes a function which takes no arguments and you must return an observable sequence.

    // observableFactory : () -> Observable
    
    Rx.Observable.Defer = function(
    	observableFactory);
    

    Then once we have deferred our UI update, then we need to add it on to our existing observable using Concat so that we count down to zero before repeating.

    Rx.Observable.prototype.Concat = function (
    	o1);
    

    And once we Concat, we repeat it all over again to keep querying and counting down.  We can now run our observable sequence by calling Subscribe with no arguments (since we’re not doing anything with the results).

    $(document).ready(function() {
        Rx.Observable.Defer(function() { return updateUI(); })
            .Concat(countdownUI())
            .Repeat()
            .Subscribe();
    });

    Putting the code all together, we’re able to watch this in action where it queries Twitter for mentions of 4sq.com and displays the first result every 90 seconds.

    image 

    You can find the entire code for this example here.

    Side Note

    Just as a side note, many of these scenarios that I’ve been doing for this series apply to the Reactive Extensions for .NET as well.  For example, we could do something similar in C# that we had above.  For example, we could have our two services, each of which return nothing (Unit in this case), but do their actions as a side effect instead.

    IObservable<Unit> UpdateResults() 
    {
        return SearchTwitter()
            .Select(data => data.results[0])
            .ObserveOnDispatcher()
            .Do(result => Item.Result = result)
            .Select(_ => new Unit());
    }
    
    IObservable<Unit> Countdown()
    {
        return Observable.GenerateWithTime(
                90,
                time => time >= 0,
                time => time,
                _ => TimeSpan.FromSeconds(1),
                time => time - 1)
            .ObserveOnDispatcher()
            .Do(time => Item.Refresh = TimeSpan.FromSeconds(time))
            .Select(_ => new Unit());
    }

    And then we can listen much like before with our JavaScript example with complete parity between the two examples.

    Observable.Defer(() => UpdateResults)
        .Concat(Countdown())
        .Repeat()
        .Subscribe();

    The difference between the two is quite small, except for the observing on the dispatcher as well as making sure that our observable sequences have the same signature of IObservable<Unit>.  In the JavaScript land, we don’t have to care since we’re dealing with a weakly typed dynamic language.  Hopefully that’ll give you a bridge between the two worlds.  In the future, I’ll make sure how to bridge the gap between the two worlds more often.

    Conclusion

    Dealing with asynchronous programming has been in the forefront of many minds in the JavaScript community.  At JSConf, there were several examples of frameworks trying to get around the idea of callbacks and instead lean more towards composition.  By utilizing the Reactive Extensions for JavaScript, we’re able to compose together asynchronous and event-based operations together and transform the results in interesting ways.  One such example is querying a system and having a public countdown until the next refresh is going to be done.  That’s just one of the many things you can do with RxJS.

    So with that, download it, and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – Custom Schedulers

    In the previous post, I talked a little bit about asynchronous method chaining and extending jQuery in a fluent style to fetch tweets from Twitter and append them to a given element.  This time I want to expand upon that post, instead of taking only one tweet, I want to take one hundred of them and then cycle through each of them at a given interval.  In order to do that, I must make use of something that I alluded to in earlier posts, and that is a custom scheduler.

    Before we get started, let’s get caught up to where we are today:

    Custom Schedulers

    Another variation on a theme from our last post could be to take instead of just one tweet, but instead, take 100 of them and then fade each one out in turn by a specified interval.  To do this, we’ll have to make use of a custom scheduler.  To create a scheduler, we need three parameters, a schedule, a schedule with time and a now parameter.  The schedule parameter provides an implementation function to the scheduler that runs an action at the scheduler’s convenience.  The schedule with time parameter provides an implementation function to the scheduler to schedule the given action at the specified time from now.  Finally, we provide a now function which provides an implementation function to the scheduler with the timer’s notion of the current time.

    // schedule : action -> disposable
    // scheduleWithTime : action -> due time -> disposable
    // now : () -> time
    
    Rx.Scheduler = function(
        schedule,
        scheduleWithTime,
        now);

    With this new found knowledge, we can create our own custom scheduler which takes a delay in milliseconds to create a scheduler.  We can create our Rx.Scheduler by passing in our three functions, the schedule, the schedule with time and the notion of now.  Let’s break each function parameter down one by one.

    The schedule function takes a given action and then makes a call to window.setTimeout with our action and our delay which allows us to evaluate the action after the given span.  We then return a Disposable which then gives us the ability to cancel the timeout with our given id from our setTimeout should we need to.

    function(action) {
        var id = window.setTimeout(action, delay);
        return Rx.Disposable.Create(function() { 
            window.clearTimeout(id); });
    },

    The schedule with time function takes given action and a due time, and like before, it makes a call to window.setTimeout but this time with the action and the given due time.  And just as before, we create a Disposable to allow us to clean up and cancel the timeout should we need to. 

    function(action, dueTime) {
        var id = window.setTimeout(action, dueTime);
        return Rx.Disposable.Create(function() { 
            window.clearTimeout(id); });
    },

    Finally, the now parameter takes no arguments and we’ll simply return the current time. 

    function() {
          return new Date().getTime();
    });

    When we put these together we can create our custom DelayedScheduler such as the following:

    var delayedScheduler = Rx.DelayedScheduler = function(delay) {
    
         return new Rx.Scheduler(
            function(action) {
                var id = window.setTimeout(action, delay);
                return Rx.Disposable.Create(function() { 
                    window.clearTimeout(id); });
            },
            function(action, dueTime) {
                var id = window.setTimeout(action, dueTime);
                return Rx.Disposable.Create(function() { 
                    window.clearTimeout(id); });
            },
            function() {
                return new Date().getTime();
            });
    };

    Now that we’ve defined our custom scheduler, it’s time to put it to use.  What we’re going to do is take the array of our tweets from Twitter and put the delay between them.  To do that, we’ll make use of the Rx.Observable.FromArray method which takes not only the array we want to turn into an observable, but also a custom scheduler should we need one.  We’ll create an extension to the Array class which allows us to turn our arrays easily into observables.

    Array.prototype.toObservable = function(scheduler) {
        return Rx.Observable.FromArray(this, scheduler);
    }

    Once the extension has been defined, let’s do something useful with it.  We’ll take the approach once again from the previous post to get tweets, but this time, we’ll take the maximum we can, which is 100 and then space each one out accordingly, and then rinse and repeat after we’ve exhausted our 100 tweets.  In our subscription, we’ll fade in and fade out our text as we append it to the content to give ourselves a rolling feel to it.

     

    var url = "http://search.twitter.com/search.json?q=4sq.com&rpp=100";
    var customScheduler = new Rx.DelayedScheduler(5000);
    
    $.ajaxAsObservable({
                url: url,
                type: "get",
                dataType: "jsonp",
            })
        .SelectMany(
            function(d) {
                return d.data.results.toObservable(customScheduler);
            })
        .Repeat()
        .Subscribe(
            function(result) {
                $("<p/>")
                    .fadeTo(1000, 1.0)
                    .html(result.text)
                    .fadeTo(1000, 0.1)
                    .appendTo("#content");
            });

    When we fire up our browser of choice we can see the fruits of our labor such as the following with proper spacing between the two and nice effects fading in and out.

    image

    And there you have it, using a custom scheduler to take data we already have and spread it out over time.  The idea here is to not tax the remote server, but instead query the system once, display all the results and then hit the server again once we’ve exhausted the data source.  You can find the complete example of this code here.

    Conclusion

    Dealing with asynchronous programming has been in the forefront of many minds in the JavaScript community.  At JSConf, there were several examples of frameworks trying to get around the idea of callbacks and instead lean more towards composition.  By utilizing the Reactive Extensions for JavaScript, we’re able to compose together asynchronous and event-based operations together and transform the results in interesting ways.  For example, we can query a system for the data, space it out over time and then requery the system for more as we need it.  That’s just one of the many things you can do with RxJS.

    So with that, download it, and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – Async Method Chaining

    Recently, there was a blog post by Dustin Diaz about method chaining over asynchronous operations.  This topic, of course is near and dear to my heart as it strikes the exact chord of what the Reactive Extensions for JavaScript (RxJS) is trying to solve.  The ability for us to take asynchronous operations and events and treat them as push collections, we are able to then compose functions together as if they were normal pull collections like arrays.  In this post, I’ll walk through the example that was posted on Dustin’s site and show how it can be done using RxJS.

    Before we get started, let’s get caught up to where we are today:

    Asynchronous Method Chaining

    To show off some of the power of the Reactive Extensions for JavaScript, let’s take the example of creating a paragraph, populating it from a single tweet from Twitter, adding a class and finally appending it to a div element.  Just as well, we want to optionally give you a way to gracefully handle errors should the data source not be available.  And when has that ever happened to Twitter, I mean really??!!

    $("<p/>")
        .fetch("http://search.twitter.com/search.json?q=4sq.com&rpp=1")
        .addClass("loading")
        .appendTo("#content");
        
    // Or
    var errHandler = function(exn) {
        // Do something with the exception
    }
    
    $("<p/>")
        .fetch("http://search.twitter.com/search.json?q=4sq.com&rpp=1", errHandler)
        .addClass("loading")
        .appendTo("#content");

    This is fairly simple to do through the use of a little jQuery and RxJS knowledge.  First, we’ll extend the jQuery fn with a function called fetch which takes a URL and an optional onError handler which is a function that takes an exception and returns no value.  Depending on whether the error handler was supplied or not, we’ll create an observer from the onNext which sets the tweet into the innerHTML of the jQuery selector.  We’ll then call the ajaxAsObservable extension which comes with RxJS to turn the ajax function into an observable, and subscribe with our observer.  Finally, we return the context of the selector as the result of the function which allows us to continue chaining calls.

    (function($) {
    
        $.fn.fetch = function(url, onError) {
            var collection = this;
    
            var onNext = function(d) { 
                $(collection).html(d.data.results[0].text); 
            }
            
            var observer = onError ? Rx.Observer.Create(onNext, onError) : onNext;
    
            $.ajaxAsObservable({
                url: url,
                type: 'get',
                dataType: 'jsonp',
            })
                .Subscribe(observer);
    
            return this;
        };
    
    })(jQuery);

    That’s a fairly simple scenario for using this, so, how about something a bit more complex like fetching the results at a given interval?  We could then create a function called fetchEvery which takes a specified interval to call the AJAX service and populate the selector by using the Interval method with our desired interval.

    $.fn.fetchEvery = function(url, interval, onError) {
        var collection = this;
    
        var onNext = function(d) { $(collection).html(d.data.results[0].text); }
        var observer = onError ? Rx.Observer.Create(onNext, onError) : onNext;
    
        Rx.Observable.Interval(interval)
            .Select(function() {
                return $.ajaxAsObservable({
                    url: url,
                    type: 'get',
                    dataType: 'jsonp',
                }); })
            .Switch()
            .Subscribe(observer);
    
        return this;
    };

    And then we could use it much like the following where we fetch the results every 5 seconds.

    $("<p/>")
        .fetchEvery("http://search.twitter.com/search.json?q=4sq.com&rpp=1", 5000)
        .addClass("loading")
        .appendTo("#content");

    But what about further transforming the data as it comes back, such as the example of censoring the swear words and create links from the text?  Well, instead of living inside jQuery and sprinkling in RxJS like we have been doing for the past couple of examples, we can then decide that instead we’ll live inside RxJS and sprinkle in jQuery.  We’ll create functions to censor the text, linkify it, handle any exceptions and finally handle the text as it comes in so that we can add it to the content.

    function handleText(text) {
        $("<p/>").html(text).addClass("loading").appendTo("#content");
    }
    
    function errHandler(exn) {
        // handle exception
    }
    
    function censorTweet(uncensored) {
        // handle censoring
    }
    
    function linkify(tweet) {
        // linkify tweet
    }
    
    $(document).ready(function() {
    
        $.ajaxAsObservable({
            url: "http://search.twitter.com/search.json?q=4sq.com&rpp=100",
            type: "get",
            dataType: "jsonp",
        })
            .Select(function(d) { return d.data.results[0].text; })
            .Select(censorTweet)
            .Select(linkify)
            .Subscribe(handleText, errHandler);
    });

    This gives us the ability now to get the data from Twitter, censor it if necessary, create real links from the text, and finally put the results into our content in a fluent style while mixing in jQuery where we need to.  Just as well, I could have used any other library including Dojo, ExtJS, YUI, Prototype, Moo Tools or whatever I felt like, so I’m not particularly tied here to a certain library and I get the same win from each.

    Conclusion

     

    Dealing with asynchronous programming has been in the forefront of many minds in the JavaScript community.  At JSConf, there were several examples of frameworks trying to get around the idea of callbacks and instead lean more towards composition.  By utilizing the Reactive Extensions for JavaScript, we’re able to compose together asynchronous and event-based operations together and transform the results in interesting ways.  We can also live well inside the given frameworks such as jQuery and sprinkle in RxJS, or we can live in RxJS and sprinkle in the calls to the various libraries such as jQuery, Moo Tools, Prototype, and so forth.

    So with that, download it, and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – Refactoring a Game

    We’ve covered a lot of ground so far in this series including a lot of the combinators as well as the integration into third party libraries.  Most of these examples have been from a green field mindset where we have an idea and then walk through how you would accomplish it using the Reactive Extensions for JavaScript (RxJS).  This time, we’re going to take a game that’s already been written and take parts of it and migrate it to use RxJS.

    Before we get started, let’s get caught up to where we are today:

    Refactoring Pong

    During this series, I’ve been asked to take examples from other sources and show how those ideas can be expressed using RxJS.  In this series, I’m going to take an existing game from an article entitled “An Introduction to Game Programming with JavaScript” where the pong example is written in plain ol’ JavaScript and involves some events and callback scenarios.  What I will do is take this example and walk through step by step how to think differently about the application and how RxJS, with the addition of jQuery, can help.  After all, just sprinkling in a little jQuery everywhere can’t hurt, right?  Even for the simple case of adding two numbers together

    Anyhow, let’s start with the beginning to understand how this application works.  We have a simple page with a paddle and a ball and a place to display the score.

    <body onLoad="init()">
        <h1>Rebound</h1>
        <div id="playingArea">
            <div id="paddle">
                <img src="paddle.gif">
            </div>
            <div id="ball">
                <img src="ball.gif">
            </div>
            <div id="score">
                Score: 0
            </div>
        </div>
    </body>

    As you may notice, we have a body.onLoad defined which calls in init function.  This init function initializes the elements for the paddle, ball and score, registers the event handler for the keydown event and then starts the main loop.

    function init(){
        //instantiate HTML object instance vars
        ball = document.getElementById('ball');
        paddle = document.getElementById('paddle');
        score = document.getElementById('score');
        //register key listener with document object
        document.onkeydown = keyListener;
        //start the game loop
        start();
    }

    Let’s refactor this a little bit so that we use jQuery selectors, as well as refactoring how the keydown events are handled.  You’ll notice we created a function to initialize our handlers which I’ll cover shortly.

    $(document).ready(function() {
    
        ball = $("#ball");
        paddle = $("#paddle");
        score = $("#score");
        
        initializeHandlers();
        
        start();
    }

    Previously, we hooked our keydown event handlers on our document by using the keyListener function.  This function listened for either the left or right arrow and then moved the paddle appropriately by four pixels depending on the direction desired.

    function keyListener(e){
      if(!e){
          //for IE
          e = window.event;
      }
      if(e.keyCode==37 && paddleLeft > 0){
          //keyCode 37 is left arrow
          paddleLeft -= 4;
          paddle.style.left = paddleLeft + 'px';
      }
      if(e.keyCode==39 && paddleLeft < 436){
          //keyCode 39 is right arrow
          paddleLeft += 4;
          paddle.style.left = paddleLeft + 'px';
      }
    }

    Instead, what we’re going to do is separate the concerns of each key, the left and right arrow, into different observables and then when we subscribe, we modify the location of the paddle in the appropriate direction.  To do this, we’ll get the keyDown observable by taking our document and calling toObservable.  Then for the left arrow handler, we’ll filter out all keys but the left arrow while we’re still in bounds, and then in the Subscribe, we move the paddle to the left by 4 pixels.  The same applies to the right arrow as well, but the difference is that we move the paddle to the right by 4 pixels.

    function initializeHandlers() {
        var keyDown = $(document).toObservable("keydown");
        
        // Left arrow
        keyDown
            .Where(
                function(ev) { 
                    return ev.keyCode===37 && paddleLeft > 0; 
                })
            .Subscribe(
                function() {
                    paddleLeft -= 4;
                    paddle.css("left", paddleLeft + "px");
                });
    
        // Right arrow
        keyDown
            .Where(
                function(ev) { 
                    return ev.keyCode===39 && paddleLeft < 436; 
                })
            .Subscribe(
                function() {
                    paddleLeft += 4;
                    paddle.css("left", paddleLeft + "px");
                });
            
    }

    Next, let’s look at the overall game loop.  This sets the ball in motion so that we can react with our paddle to ensure that we hit it and continue the game until we miss and the game ends.  This function first detects if there are collisions, then renders our movement and then increases the difficulty of the game (hint: the ball moves faster).  If by the end of this, the ball is still in play, then we wait for 50 milliseconds and then start the loop all over again, else we say that the game is over.

    function start() {
        //game loop
        detectCollisions();
        render();
        difficulty();
        
        //end conditions
        if(ballTop < 470){
            //still in play - keep the loop going
            timer = setTimeout('start()',50);
        }
        else {
            gameOver();
        }
    }

    Now when it comes to porting this to the Reactive Extensions for JavaScript, we have to turn the problem on its ear a little bit.  What are we doing anyways?  At specified intervals, we’re doing a certain action which modifies our environment while our ball is in play and if it somehow isn’t, we end the game.  And just as easily as I described it above, we can write this in RxJS.  First, we start out at an interval of 50 milliseconds by calling Rx.Observable.Interval, and at each interval, we want to perform some actions, like detecting collisions and so forth that we did above.  We can accomplish that with the Do function which handles those three function calls.  Now we need to check if we’re still in bounds, so we can use the TakeWhile function to specify what is in bounds, and in this case, the top of the ball is less than 470.  And finally, once our TakeWhile no longer returns true, we’ll want to end the game, and we can do that by using the Finally function to invoke the gameOver function.

    function start() {
        //start the game loop
      Rx.Observable.Interval(50)
          .Do(
                function() {
                  detectCollisions();
                  render();
                  difficulty();
              })
          .TakeWhile(function() { return ballTop < 470; })
          .Finally(function() { gameOver(); })
          .Subscribe();
    }

    And there you have it, we can react just the same as we did above, although we did tack on an additional 50 ms to the front end.  I’ll cover more of how we can use RxJS to break the problem into smaller building blocks and using the combinators of RxJS, put it back together.

    Conclusion

    What we’re able to do now is to break our problems into logical pieces and by using the Reactive Extensions for JavaScript functions, we can glue them together to create composable solutions.  At some points, it can be a little difficult, just as it was for many to move from imperative looping over collections to declarative composable actions over these collections, but the reward is just as great.

    So with that, download it, and give the team feedback!

    Read more...

  • Introduction to the Reactive Extensions for JavaScript – Going Parallel with ForkJoin

    This past week there was a new release of the Reactive Extensions for JavaScript which includes many of the changes I’ve been talking about lately including the third-party library integration, aggregates and joins which I covered in the previous posts.  This time, I’m going to look at how we can run some observable sequence using the fork/join pattern in JavaScript, to attain some cooperative multi-tasking.

    Before we get started, let’s get caught up to where we are today:

    Going Parallel with ForkJoin

    One common asynchronous pattern that is often used is called fork/join where we start with a specified number of tasks and later we join together all the work.  Let’s first take a look at a simple model of what we’re trying to do.  Say we want to have the ability to load a few scripts in JavaScript?  Typically, we’d have an array of sources we want to visit and then we’d process each in turn and then return the overall result as an array.

    var results = [];
    var urls = [url1, url2, url3];
    
    for(var task in tasks) {
        results.push(loadScript(tasks[task]));
    }

    The problem with this approach is that it is a blocking scenario in that we must wait for each one to execute in turn, so the browser can do nothing else in the mean time.  Just as well, each of our operations do not depend on the other, so we could, hypothetically, run them in cooperation with each other if we had a good way of doing so.  This would easily qualify as an embarrassingly parallel solution.

    But how do we do it?  After all, we want to run these as non-blocking calls and we want to run them in parallel.  With the asynchronous behavior, that brings any number of issues such as error handling, cancellation checking and so forth.  Luckily, with the Reactive Extensions for JavaScript, we have that part covered with the ability to compose asynchronous operations together.  But, what about running them in parallel?  That’s where the function ForkJoin comes into play.

    The ForkJoin function in the Reactive Extensions for JavaScript allows us to take all observable sequences and run them in a cooperative fashion and return their first values in an array.  This function takes a variable amount of arguments, depending on how many observable sequences you have.

    Rx.Observable.ForkJoin = function(
        obs1,
        ...
        obsx);

    Just as well, in a future version that is not out yet as of this writing will also support an array as the first argument such as:

    Rx.Observable.ForkJoin = function(
        observableArray);

    Now, let’s run through a quick example of using ForkJoin.  In this example, I’m going to check the flight status of a given number of flights, in case I have to coordinate a bunch of people coming into town.  To do this, I can use the Bing Instant Answer API to do that and return the answers in JSON format. 

    function flightStatus(flight) {
        var serviceUrl = "http://api.bing.net/json.aspx";
    
        return $.getJSONAsObservable(
            serviceUrl,
            { appId : appId,
              Query : flight,
              Sources : "InstantAnswer",
              Market : "en-us",
              Version : "2.2" })
            .SelectMany(
                function(d) {
                    return d.data.SearchResponse.InstantAnswer.Results.toObservable();
                });
    
    }

    Once we’ve defined our function to get the flight status, let’s start with a few flight numbers.

    var flights = ["UA123","UA124","UA125"];

    Now, we need to take those flight numbers and then turn them into observable sequences by using the jQuery map function which takes the sequence and applies a function to each element.

    var flightsAsObservables = $.map(flights, function(flight) { 
        return flightStatus(flight); })

    And now we can call ForkJoin to run these in parallel and return them in the order in which we sent them.  We’ll then iterate over the array of results and output the departure and arrival airport and associated times.

    Rx.Observable.ForkJoin(flightsAsObservables)
        .Subscribe(function(results) {
    
            $.each(results, function(_,result) {
                var status = result.InstantAnswerSpecificData.FlightStatus;
    
                $("#translatedText")
                    .append("<li>Flight: "+ status.FlightName +
                        " from " + status.OriginAirport.Name +
                        " to " + status.DestinationAirport.Name +
                        " departs at " + status.ScheduledDeparture +
                        " arrives at " + status.ScheduledArrival + "</li>");
    
            });
        });
    

    And there you have it, we’re now able to run computations in a cooperative multi-tasking environment and return the result as an array, and in this case, getting the flight schedules for a number of flights we wish to track.

    Conclusion

    Using the Reactive Extensions for JavaScript, we’re able to run observable sequences together and get the result as an arry using a well defined pattern of fork/join in JavaScript.  That’s just one of the many things we can do with it that I’ll hopefully cover more in the near future.  So, download it, and give the team feedback!

    Read more...

  • [ANN] DC ALT.NET – 4/27/2010 – What has Mono done for the .NET developer lately?

    As of late I haven’t posted the DC ALT.NET meetings here and instead have kept them to the Yahoo Groups mailing list.  But this month’s topic is worth sharing in that we’re going to cover everything Mono related with a member of the Mono Team, Jackson Harper

    If you’re not familiar with Mono, it is an open-source, cross-platform implementation of the .NET framework based on the ECMA standards for C# and the Common Language Infrastructure. With Mono, users can run .NET applications written and compiled in Visual Studio on Windows, Linux, and Mac OS X. This session will provide an introduction to cross-platform development and deployment with Mono.  Participants will see how they can leverage their existing skills and tools to write .NET applications that will run on multiple platforms and architectures with Mono. The presentation will also include a discussion of cross-platform considerations for leveraging Mono, and demonstrate how to use MoMA, the Mono Migration Analyzer, to determine how ready an application is for cross-platform deployment.  Additional demonstrations will examine how best to leverage Visual Studio to develop and deploy to Linux and OS X, and take a peek at the current state of Moonlight 3 and 4.

    Hope to see you there!

    Register for DC ALT.NET - 4/27 - What has Mono Done for .NET Developers Lately? in Alexandria, VA  on Eventbrite

    Read more...