Increasing the Reactiveness Using Operators

Learn about JSONP and the usage of the flatMap operator.

We'll cover the following

What is JSONP?

JSONP, or JSON with padding, is a sneaky technique that web developers came up with to work around browser restrictions when requesting data from third-party domains.

JSONP bypasses these restrictions by loading external content with script tags, instead of the usual XMLHttpRequest. Adding a script tag to the DOM loads and executes its content directly, and the security restrictions are not applied.

The remote request’s content is, then, a normal JSON wrapped in a function call (the “P” in JSONP). It looks like this:

callbackFn({ a: 1, b: 2, c: 3})

JSONP URLs usually accept a query string parameter, so that the caller can specify the name of the callback. The developer then has to define a function in their code that has the same name as the callback in the server response, and when the script tag is added to the document, that function will be called with the JSON data as the first parameter.

Libraries like jQuery automate this process by internally creating the global function to handle the JSONP call, and tidying it up afterward to avoid polluting the global namespace.

Going deeper

Can we do better? You bet! In the preceding code, we’re still managing the flow by traversing the array and calling onNext to yield each earthquake, even if we isolated it inside the Observable. So much for reactiveness!

This is a perfect situation for flatMap. We’ll retrieve the data and make an Observable out of the features array, using Rx.Observable.from. Then, we’ll merge that Observable back in the main Observable:

Get hands-on with 1200+ tech skills courses.