Hot and Cold observables

One important thing to understand when you are working with Reactive Programming is the difference between hot and cold observables.
Let’s start with the definition of both types:

Cold Observables

Cold observables start running upon subscription: the observable sequence only starts pushing values to the observers when subscribe is called.

Values are also not shared among subscribers.

Hot Observables

When an observer subscribes to a hot observable sequence, it will get all values in the stream that are emitted after it subscribes.

The hot observable sequence is shared among all subscribers, and each subscriber is pushed the next value in the sequence.

Let’s see now how these 2 different observables are used across a sample application.

Using the same application I started to describe in my previous blog post, we can spot in the main class some code that is commented.
The first part represent how a cold observable works, so if you try to have the following code inside App.js you can immediately understand what’s going on when an observer subscribes to a cold observable:

let engine = new BallsCallSystem(); 
let t1 = new Ticket("t1", engine.ballStream); 

    let t2 = new Ticket("t2", engine.ballStream);
}, 5000);


Our game engine instead has the following code in order to share the balls called across the tickets:

let stream = Rx.Observable
    .map((value) => {return numbersToCall[value]})
this.published = stream.publish();

As you can see when we start the game there is only 1 ticket bought by the user, then after 5 seconds the user bought a new ticket and in theory we should check if in that ticket all the numbers previously called are present or not.

But with cold observables when an observer subscribe, it won’t be able to receive the previous data but just the data since when it subscribed, completely broken the main purpose of our bingo game… we definitely need something different in order to work with it, potentially something that won’t completely change our game logic but that could be useful to fix the issue…

That’s where the hot observables come in!
The cool part of hot observables is that you can define how much data you want to buffer inside the memory, sometimes you need to store all of them (like in the bingo game) sometimes you need only the last 4-5 occurrences, but as you will see changing from a cold to an hot observables it’s a matter of 1 line of code!

Inside the same git repo, you can find a class called BallsCallSystemReplay, this class implement an hot observable, let’s see how much the code changed inside our game engine: = Rx.Observable
   .map((value) => {return numbersToCall[value]})

Basically we removed the publish method after creating the stream (that was useful if you want to control when the observable starts to stream data) and we added shareReplay that is a method that transform a cold observable to an hot one sharing all the data pass trough the stream every time a new observer subscribe to it.

So now if we change the code in App.js in this way:

let engine = new BallsCallSystemReplay();
let t1 = new Ticket("t1", engine.ballStream);
setTimeout(function() {
    let t2 = new Ticket("t2", engine.ballStream);
}, 5000);

Now you can see that when the second ticket is bought after the game started, we’re going anyway to check all the values called by the engine without doing a massive refactor of our game logic! Below you can see when the second ticket subscribe to the hot observable, the first thing is going to receive are all the previous values called by the engine and then is receiving the data with a certain interval following the logic of the game.



Reactive Programming with RxJS

In the past 6 months I spent quite few time trying to understand Reactive Programming and how it could help me on my daily job.
So I’d like to share in this post a quick example made with RxJS just to show you how Reactive Programming could help when you are handling asynchronous data streams.

If you are not familiar at all with these concepts I’d suggest to watch first my presentation on Communicating Sequential Process and Reactive Programming with RxJS (free registration) or check the slides below.

For this example I thought to create a basic bingo system that I think is a good asynchronous application example that fits perfectly with the Reactive Programming culture.
I won’t introduce in this blog post concepts like hot and cold observables, iterator pattern or observer pattern mainly because all these theoretical information are present in the webinar and the slides previously mentioned. 

You can clone the project repository directly from my git account.

Let’s start talking a little bit about the engine, basically a bingo system is composed by an engine where the numbers are called every few seconds and shared with the users in order to validate in which ticket bought by the user the number called is present.
For this purpose working with observables will facilitate the communication and the information flow between the engine and the ticket objects.
In BallsCallSystem class, after setting up the object creating few constant that we’re going to use inside the core engine, we’re going to implement the core functionality of the engine:

let stream = Rx.Observable
              .map((value) => {return numbersToCall[value]})

These few lines of code are expressing the following intents:

  1. we create an observable (Rx.Observable)
  2. that every few milliseconds (interval method)
  3. iterate trough the interval values (incremental value from 0 to N) and return a value retrieved from the array numbersToCall (function described inside the map method)
  4. and after a certain amount of iteration we need to close the observable because the game is ended (take method) so all the observer will stop to execute their code

If we compare with an imperative programming implementation made with CSP (communicating sequential processes) I’ll end up having something similar to this one: = setInterval(this.sendData.bind(this), 3000);
   var val = this.numbersToCall[this.counter];
   console.log("ball called", val);
   csp.putAsync(, val);
   if(this.counter > this.numbersToCall.length){
      console.log("GAME OVER");

As you can see I needed to express each single action I wanted to do in order to obtain the core functionality of my bingo system.
These 2 implementations are both solving exactly the same problem but as you can see the reactive implementation is way less verbose and easy to read than the imperative one where I’ve control of anything is happening inside the algorithm but at the same time I don’t really have a specific reason to do it.

Moving ahead with the reactive example, when we create an observable that streams data we always need an observer to retrieve these data.
So now let’s jump to Ticket class and see how we can validate against a ticket the numbers called by the engine

First of all we pass the observable via injection to a Ticket object:

let t2 = new Ticket("t2", engine.ballStream);

Then, inside the Ticket class we subscribe to the observable and we handle the different cases inside the stream (when we receive data, when an error occurs and when the stream will be terminated):

obs.subscribe(this.onData.bind(this), this.onError.bind(this), this.onComplete.bind(this));
    console.log("number called", value, this.tid);
    if(this.nums.indexOf(value) >= 0){
       console.log(value + " is present in ticket " + this.tid);
    console.log("stream error:", err);
    console.log("total numbers called in " + this.tid + ": " + this.totalNumsCalled.length);

Also here you can notice the simplicity of an implementation, for instance if we are working with React it will be very easy to handle the state of an hypothetical Ticket component and create a resilient and well structured view where each stream state is handled correctly.

An interesting benefit provided by reactive programming is for sure the simplicity and the modularity at the same time how our implementations are working.
I would really recommend to spend sometime watching the webinar in order to get the first approach to Reactive Programming and to understand better the purpose of the example described briefly above.

Scotch on the Rocks 2010

It’s finished!!! DAMN!

SOTR 2010 is end, I hope to come again next year, but now I want to share with you my experience here in London.

SOTR was organized at TigerTiger club near Piccadilly circus in the heart of London and believe me, It’s my first time that I take part in a conference where stop for a couple of days a club! That’s totally crazy, but this is SOTR and I love it! (Obviously free drink inside ;P)

Location a part, sessions were pretty cool, I really appreciate Aral and Serge one, the first was an inspire session based on clients UX and I grabbed very cool suggestions; Serge’s session was about AIR 2 and Flash Player 10.1 on Android devices… I really love those stuff!
It was impressive a performance benchmark where the same animation created with HTML and JS (7fps), another made with HTML 5 and canvas (9fps) and one made with Flash Player 10.1 (25fps !!! I really love Flash Platform) obtains different results on Android… and what results!!!

I was at SOTR also to speak about AIR 2 printing API, AlivePDF and PurePDF, I made an inspire session that allow you to have the right solution when someone (your boss maybe?!) ask you to create data reports or paper documents in a Flex RIA or AIR application.
My English a part, I think that people enjoy case history part and first twitter messages are agree with me, so believe me guys at SOTR, thank you so much for your time.
Finally in my session I shared my “thoughts” about HTML 5, Apple and so on (many photos on this slide, I was sure that you appreciate it! :D).

You can download all the stuff made for AIR & Printing session directly from this blog and if you weren’t in London and you want ask me more details about this cool shit, feel free to contact me or leave a comment at this post!

Ok, it’s time to come back to reality but before that I must say a big THANK YOU to Andy Allan that organize this amazing event, Cyril and Guust (and his girlfriend) for the great time spent together in London talking about Coldfusion and our beautiful countries.

Second day at Flash on the Beach 08… Flash 10 on IPhone

Second day is finished, but it was very intensive!
I saw lots of interesting session, first of all Mr. Aral Balkan that showed us how to have fun with our work and that we must take time to experiment and try new languages, very interesting session.

Then, my favourite, Adobe Town Hall, where they said: “Yes we are working on Flash 10 on iPhone!”.
I hope that they don’t put a “slim” version without important API like the newest that allow to work with local files with Flash Player in a browser.
I asked also if with AIR 2 they will solved the problem of interaction with others applications embedded on a mobile phone and if it update itselfs without download a new firmware… they said… “Open Screen Project solved the second issue and the first one… yes we are working on this way”.
Great news for mobile developers!

Then I saw Grant Skinner with a cool sesson about  what a Flash developer should know… 

Peter Elst talked about AIR api and show interesting things with Merapi Projects and Adobe AIR… the speech to text sample was amazing!

Lee Brimelow showed us about new Adobe product releases like Flex 4, new features of Flash CS4 and so on, it’s an amazing speaker because he show stuff with a fun.. like a joke… cool!

Tomorrow I will attend the last day, there will be lots of interesting things to take a look… Nicolas session for example… see you tomorrow guys

AIR tour, last date in Milan

AIR tour is finished! Last date was in Milan and obviusly was very cool!

Location was pretty nice, great organization, cool food and a lots of stuff (T-shirt is amazing!).
A very friendly atmosphere, Adobe guys made a great overview about AIR from the beginning to final deployment.
I appreciate a lots Serge Jesper and Andrew Shorten‘s session, they talked about how to deploy and sign an AIR application and a great overview about LCDS and Blaze DS.
But my favourite one was Brimelow‘s session, he showed a lots of cool samples and in a very cool and funny way.

This weekend I’ll publish all photos made during the event in my Flickr account


BRIO Beta: web meeting service

Adobe release a new BETA in called BRIO that is codename of new version of Acrobat Connect (ex Breeze).
I’m working with it now, there are many alert when you try to upload files or in other featuers BUT…
… what a great UI!

It’s more easy to use, main functions are available like icons and it’s so fast!

The most impressive features you could see when you share your desktop, in fact you have a “widget” to chat with others users, you can see other users in your room and you have a little panel control to manage.
Very cool!

Now you can test it and create your room for FREE!

So go to BRIO page and test it man!