When an Observer subscribe to a BehaviorSubject. It receivces the last emitted value and then all the subsequent values. BehaviorSubject requires that we provide a starting value, so taht all Observers will always receive a value when they subscribe to a BehaviorSubject.

Imagine we want to retreve a remote file and print its contents on an HTML page, but we wnat placeholder text while we wait for the contents. We can use a BehaviorSubject for this.

var subject = new Rx.BehaviorSubject('Waiting for content');
subject.subscribe(
function(result) {
document.body.textContent = result.response || result;
},
function(err) {
document.body.textContent = 'There was an error retrieving content';
}
);
Rx.DOM.get('/remote/content').subscribe(subject);

Example 2:

var subject = new Rx.BehaviorSubject();

var observerA = {
next: function (x) { console.log('A next ' + x); },
error: function (err) { console.log('A error ' + err); },
complete: function () { console.log('A done'); },
}; subject.subscribe(observerA);
console.log('observerA subscribed'); var observerB = {
next: function (x) { console.log('B next ' + x); },
error: function (err) { console.log('B error ' + err); },
complete: function () { console.log('B done'); },
}; subject.next();
subject.next();
subject.next(); /*
0---1---2---3---------------
0..1...2...3...
3.....
*/ setTimeout(function () {
subject.subscribe(observerB);
console.log('observerB subscribed');
}, );
/*

"A next 0"  <-- Always get the init value
"observerA subscribed"
"A next 1"
"A next 2"
"A next 3"
"B next 3" <-- Because A & B share the same observer, B will receive last emit value
"observerB subscribed" */

最新文章

  1. C/C++浮点数在内存中的存储方式
  2. JsonFormatter PrettyPrint
  3. install Hadoop
  4. Delphi面向对象---接口
  5. Kerberos安装及使用
  6. &lt;mvc:annotation-driven/&gt;与&lt;mvc:default-servlet-handler/&gt;之间的一个问题
  7. numpy.concatenate
  8. Log4j配置与使用
  9. Entity Framework 系统约定配置
  10. 爆破vcrkme01(已补上注册机)
  11. C# Obsolete
  12. win10 Administrator
  13. JavaScript的应用
  14. 实战weblogic集群之创建节点和集群
  15. 访问祖先类的虚方法(直接访问祖先类的VMT,但是这种方法在新版本中未必可靠)
  16. HDU 5933/思维
  17. 201521123081《Java程序设计》 第9周学习总结
  18. 基于Spring、SpringMVC、MyBatis、Druid、Shrio构建web系统
  19. linq之左连接 + group by
  20. nginx反向代理转发后页面上的js css文件无法加载【原创】

热门文章

  1. 10.cocos2d坐标系
  2. Atcoder AGC 019 A,B
  3. Dubbo简易学习
  4. 小米开源文件管理器MiCodeFileExplorer-源码研究(4)-文件操作工具类FileOperationHelper
  5. Myeclipse学习总结(2)——MyEclipse快捷键大全
  6. POJ——T 2796 Feel Good
  7. 15.Node.js REPL(交互式解释器)
  8. Filebeat之input和output(包含Elasticsearch Output 、Logstash Output、 Redis Output、 File Output和 Console Output)
  9. C#截取中英文混合字符串分行显示
  10. map(froeach改变值,map生成新数组)