I am not sure how correct I am on this so if any experts are able to correct me on this it would also be appreciated. My current understanding is that observables are lazy and do not produce values until subscribed to. If an error occurs the observable sends no more values. In a lot of cases this is not what is wanted.
In the code sample below I am getting the weather for perth and london and if an error occurs returning an object indicating the error has occured. This pretty much means that the error block on the subscriber will not get called but the success will and I will have to look at whether it failed and change logic. Is this the best way to do this????
Also does the zip operator wait for all obs to produce a value regardless of ordering and return when a single value from all has been produced?
Code as below:
window.application = application || {};
window.application.stocks = (function(){
function getWeather(city, country){
return $.ajaxAsObservable({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country,
dataType: 'jsonp'
}).map(function(v){
return {
city : city,
country : country,
temperature : v.data.main.temp
};
});
}
var requests = Rx.Observable
.interval(500)
.timestamp()
.map(function(v){
var perth = getWeather('perth','au');
var london = getWeather('london','uk');
return Rx.Observable.zip(perth,london, function(a,b){
return {
a : a,
b : b,
timestamp : v.timestamp,
failure : false,
};
}).retry(3)
.catch(Rx.Observable.return({ failure: true }));
})
.concatAll();
var selector = $('#weather');
var subscriber = requests.forEach(
function(data){
if(data.failure){
$('<li>Failure in receiving the temperature</li>').appendTo(selector);
return;
}
$('<li> at: ' + data.timestamp + ' for: ' + data.a.city + ' - ' + data.a.temperature + '</li>').appendTo(selector);
$('<li> at: ' + data.timestamp + ' for: ' + data.b.city + ' - ' + data.b.temperature + '</li>').appendTo(selector);
},
function(error){
selector.text('');
$('<li>Error: ' + error + '</li>').appendTo('#weather');
},
function(){
}
);
});
Any suggestions and tips is greatly appreciated.
Thanks in advance.
Blair.