How Do I Wrap An Existing API?
Last updated
Was this helpful?
Last updated
Was this helpful?
One question that often comes up is how can I wrap an existing API into an Observable sequence? The answer is fairly simple and not a lot of lines of code to make that happen.
To make this a bit more concrete, let's take a familiar HTML5 API like , in particular, the navigator.geolocation.watchPosition
method.
The typical use of this method might be the following where we would hook up an event handler to listen for success and errors on watching the geolocation by using the navigator.geolocation.watchPosition
method. When one wishes to terminate listening for geolocation updates, you simply call the navigator.geolocation.clearWatch
method passing in the watch ID returned from the watchPosition
method.
Our final result should look like the following:
And now we can consume the geolocation such as:
In order to wrap this, we'll need to use the method. From this, we can yield values to the observer or handle the errors. Let's see how the code might look, creating a watchPosition method which takes geolocation options.
We need to also be aware of ensuring we're not adding too many watchPosition calls as we compose it together with other observable sequences. To do that, we'll need to utilize the and methods from rx.binding.js.