我不知道我對此有多正確,所以如果有專家能夠糾正我對此,它也將不勝感激。我目前的理解是,觀察者是懶惰的,在訂閱之前不會產生價值。如果發生錯誤,observable將不會發送更多值。在很多情況下,這不是我們想要的。RxJs處理例外而不終止
在下面的代碼示例中,我得到了perth和london的天氣,如果發生錯誤並返回指示出現錯誤的對象。這很大程度上意味着訂閱者的錯誤塊不會被調用,但是成功了,我將不得不查看它是否失敗並更改邏輯。這是做這個最好的方法嗎?
此外,zip操作符是否等待所有obs生成一個值,無論訂購和返回何時生成單個值?如下面
代碼:
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(){
}
);
});
任何建議和提示是極大的讚賞。
在此先感謝。
布萊爾。
這並不一定會提供問題的答案。雖然良好的洞察力,它應該作爲評論發佈。當您獲得足夠的聲望時,您將能夠在問題,答案和其他帖子上發表評論,但在此之前,儘量不要用另一個問題回答問題。 – 2015-01-07 21:47:50