RxJava: Some Usage of Observable.zip

Posted by & filed under , .

Here’s  classic problem when dealing with a web app: you get a HTTP request to your app with a set of parameters. You need to hit a datastore to retrieve some record based on those parameters. You also need to create a (log?) entry somewhere about receiving this call — whether it’s for monitoring purposes (so you know how much load your web app is taking) or for monetary reasons (for instance if this is a call to an ad server you need to make sure you log all ad calls/impressions so you can bill your clients). You also need to invoke a method which returns some relevant information to processing the current request — imagine in the above ad-server scenario that you want to perhaps retrieve the details about the current user for instance. Then once all of these operations have completed you want to apply some processing and return your result.

Now, in “classical” Java world this would look something like this:

As you can see nothing tricky: retrieve some records, log an entry and at the end actually generate the response. Note however that because of the nature of the Java language — and the way we have written the code (I know, I know, we can write more complicated code to use thread pools and execute each one of these in its own thread in parallel, but can you imagine the overkill for writing that code to execute these 4 statements???) — these are all executed sequentially. Even though, realistically we don’t care about the order — all we care about is that the log entry gets written and we get our records read from the respective data stores by the time we get to make the call to generateAdResponse.

This is where RxJava helps provide a much nicer implementation — which also as it happens provides parallelism too. Let’s have a look at how we could wrap this up using Observable:

As you can see the trick (hardly a trick really) is to rely on Observable.zip and supply a bunch of Observable created from the calls above via some Java lambdas — these will all be run in parallel (perhaps, or not!) but it will guarantee that they all complete by the time our generateAdResponse method gets called.

I found this to be more effective then the “old fashioned” code above.

Leave a Reply

Your email address will not be published.