[RxJS + AngularJS] Sync Requests with RxJS and Angular
When you implement a search bar, the user can make several different queries in a row. With a Promise based implementation, the displayed result would be what the longest promise returns. This is the problem which we want to solve.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.22/rx.all.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="APP">
<div>
<p>Click on "Pets" then on "Nothing" in each form</p>
<p>Because pets' promise take long to resolve (longer than nothing's), it ends up with inconsistent output in Basic setup: nothing should be displayed but pets arrive!</p>
<p>RxJs is an elegant way to prevent this concurrency problems from appearing.</p>
</div>
<div ng-controller="StandardController as standard" style="margin-top:50px;">
<p>Basic setup</p>
<input id="s-pets" name="standardEntityType" type="radio" ng-model="standard.filters.entityType" value="pets">
<label for="s-pets">Pets</label> <input id="s-colors" name="standardEntityType" type="radio" ng-model="standard.filters.entityType" value="colors">
<label for="s-colors">Colors</label> <input id="s-nothing" name="standardEntityType" type="radio" ng-model="standard.filters.entityType" value="nothing">
<label for="s-nothing">Nothing</label> <p>
{{ standard.filters | json }}
</p>
<ul>
<li ng-repeat="entity in standard.entities">
{{ entity.name }}
</li>
</ul>
</div>
</body>
</html>
console.clear(); angular.module('APP', []) .service('dataService', function($q, $timeout, $rootScope){
var colors = [
{ name: 'red' },
{ name: 'blue' },
{ name: 'white' }
]; var pets = [
{ name: 'cat' },
{ name: 'dog' }
]; function fakeAjax(returnValue, delay){
return $q(function(resolve){
$timeout(function() {
resolve(returnValue);
}, delay);
});
} function getColors(){
return fakeAjax(colors, 1500);
} function getPets(){
return fakeAjax(pets, 3000);
} function nullResponse(){
return fakeAjax([], 1);
} var mapping = {
colors: getColors,
pets: getPets
}; return {
getEntities: function(type){
if (mapping[type])
return mapping[type]();
else
return nullResponse();
}
};
}) .controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; function searchEntities(type){
dataService.getEntities(type)
.then(function(entities){
controller.entities = entities;
});
} $scope.$watch(function(){
return controller.filters.entityType;
}, function(newVal){
searchEntities(newVal);
});
});
Solution 1: Add lodash _.debounce method to add some delay.
.controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; function _searchEntities(type){
dataService.getEntities(type)
.then(function(entities){
controller.entities = entities;
});
} var searchEntities = _.debounce(_searchEntities, 1500);
$scope.$watch(function(){
return controller.filters.entityType;
}, function(newVal){
searchEntities(newVal);
});
});
The problem here is we have to assume a correct time. Too long, and the UI is not responsible enough, and too short, and we may encounter weirdness again.
Solution 2: Using RxJS
.controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; var Observable = Rx.Observable;
var source = Observable.create(function(observe){
$scope.$watch(function(){
return controller.filters.entityType;
}, function(newType){
observe.onNext(newType);
});
}).flatMapLatest(function(type){
return Observable.fromPromise(dataService.getEntities(type));
}); var sub = source.subscribe(function(entities){
controller.entities = entities;
});
});
No matter what order we click the radio buttons, we'll always get the expected outcome. RxJS will handle that for us. The main benefit of RxJS over mere promises is we always get the latest query results. You can see, this implementation of Rx has a way to cancel promises.
Two methos to apply:
.controller('StandardController', function($scope, dataService){
this.entities = [];
this.filters = {};
var controller = this; var Observable = Rx.Observable;
var source = Observable.create(function(observe){
$scope.$watch(function(){
return controller.filters.entityType;
}, function(newType){
observe.onNext(newType);
});
}).debounce(500).flatMapLatest(function(type){
return Observable.fromPromise(dataService.getEntities(type));
}); var sub = source.subscribe(function(entities){
controller.entities = entities;
}); $scope.$on('destory', function(){
sub.dispose();
}); });
The first thing is to clean after yourself. On each destroy event on the scope, so basically, whenever you use a router, it could be on route change, you have to dispose the listener so Rx knows it can get rid of everything linked to it.
The second thing is we don't want to put too much pressure on our server, so we are going to use debounce again. It's very important to understand here that debounce is not a way to avoid UI issues. It's a way to avoid useless server queries.
[RxJS + AngularJS] Sync Requests with RxJS and Angular的更多相关文章
- Angular Multiple HTTP Requests with RxJS
原文:https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs ----------------------------- ...
- [Vue-rx] Cache Remote Data Requests with RxJS and Vue.js
A Promise invokes a function which stores a value that will be passed to a callback. So when you wra ...
- [AngularJS] Consistency between ui-router states and Angular directives
ui-router's states and AngularJS directives have much in common. Let's explores the similarities bet ...
- [AngularJS 2 实践 一]My First Angular App
最近一直在看关于AngularJS 2的资料,查看了网上和官网很多资料,接下来就根据官网教程步骤一步步搭建我的第一个Angular App AngularJS 2说明请参考:http://cnodej ...
- [RxJS] Refactoring Composable Streams in RxJS, switchMap()
Refactoring streams in RxJS is mostly moving pieces of smaller streams around. This lessons demonstr ...
- [RxJS] Reactive Programming - Why choose RxJS?
RxJS is super when dealing with the dynamic value. Let's see an example which not using RxJS: var a ...
- AngularJS进阶(二十五)requirejs + angular + angular-route 浅谈HTML5单页面架构
requirejs + angular + angular-route 浅谈HTML5单页面架构 众所周知,现在移动Webapp越来越多,例如天猫.京东.国美这些都是很好的例子.而在Webapp中,又 ...
- angularjs探秘<三> 控制器controller及angular项目结构
先来看一个例子 <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset=&quo ...
- AngularJS源码解析1:angular自启动过程
angularJS加载进来后,会有一个立即执行函数调用,在源代码的最下面是angular初始化的地方.代码展示: bindJQuery(); publishExternalAPI(angular); ...
随机推荐
- PHPCMS栏目调用2
{php $j=1;} {loop subcat(50) $v} {php if($v['type']!=0) continue;} ...
- Python: 设计模式 之 工厂模式例(2)(神奇的Python)
#!/usr/bin/env python #coding=utf-8 # # 工厂模式第二例(神奇的Python) # 版权所有 2014 yao_yu (http://blog.csdn.net/ ...
- iOS 仪表式数字跳动动画-b
前几天搞了 双曲线波浪动画(http://www.jianshu.com/p/7db295fd38eb)和环形倒计时动画(http://www.jianshu.com/p/d1d16dff33c9)而 ...
- 非常好用的正则表达式"\\s+" - 匹配任意空白字符
说起来,博主使用过的正则场景虽然不多,但是就是在这当中,我发现"\\s+"真好用! 详解 "\\s+" 正则表达式中\s匹配任何空白字符,包括空格.制表符.换页 ...
- Umbraco TextBoxFor 如何加样式和属性
前些天一直在找免费的CMS开源代码,搜索了很多,大都是介绍CMS开源系统的的文章或者是安装的主要流程.再深的也有但是都是很多年前的文章.我一个英语半吊子加MVC零基础只能像缓慢爬行的蜗牛一步步走了.为 ...
- Android 设置隐式意图
AndroidManifest.xml对于被调用的activity: <activity android:name="com.wuyou.twoactivity.OtherActivi ...
- TCP/IP小纪
链 路 层 主 要 有 三 个 目 的 :( 1 )为 I P 模 块 发 送 和 接收 I P 数 据 报 ; ( 2 )为 A R P 模块发送 A R P 请 求 和 接 收 A R P 应 答 ...
- Bitmap 与Drawable相互转换
Drawable 转 Bitmap import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import ...
- google font和@font-face
会使用google字体 网址: http://www.google.com/fonts/ 选择字体, quick use 引用css: <link href='http://fonts.goog ...
- 关于HttpsURLConnection的连接问题
本地测试好的项目拿到服务器上后,通过SSL连接,将Http改成Https,并指定了服务器的IP,结果连接失败.查了资料后发现,直接指定IP,SSL是无法定位连接的,实际上应该指定服务器端配置好的Hos ...