我正在努力理解为 AJAX 流显示加载指示器的“Rx”方式。
$scope.$createObservableFunction("load")
.take(1)
.do(function(){
$scope.loading = true;
})
.flatMap(contentService.AJAX_THINGY_AS_OBSERVABLE)
.delay(300)
.subscribe(function(content){
console.log("content",content);
},function(error){
$scope.error = error
},function() {
$scope.loading = false;
});
据我了解,我应该使用.do()
副作用,我认为设置loading
是,但感觉不是正确的做事方式。
谁能提供一个更清洁/更好/正确的例子来说明如何做到这一点?
谢谢!
更新 1
我决定把它分成两个流;requestSource
和responseSource
。
var loadRequestSource = $scope.$createObservableFunction("load")
.share();
var loadResponseSource = loadRequestSource
.flatMap(contentService.AJAX_THINGY_AS_OBSERVABLE)
.throttle(1000)
.share();
然后有 2 个单独的订阅者:
loadRequestSource.subscribe(function () {
$scope.loading = true;
});
loadResponseSource.subscribe(function (response) {
/* enter logic */
$scope.loading = false;
$scope.$digest();
}, function (err) {
$scope.error = err;
$scope.loading = false;
$scope.$digest();
});
我喜欢这种方法,因为它使订阅者的角色保持准确。响应订阅者不需要关心设置loading
为true
. 它只关心将其设置为false
.