[RxJS] BehaviorSubject: representing a value over time
2024-09-02 00:44:51
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" */
最新文章
- C/C++浮点数在内存中的存储方式
- JsonFormatter PrettyPrint
- install Hadoop
- Delphi面向对象---接口
- Kerberos安装及使用
- <;mvc:annotation-driven/>;与<;mvc:default-servlet-handler/>;之间的一个问题
- numpy.concatenate
- Log4j配置与使用
- Entity Framework 系统约定配置
- 爆破vcrkme01(已补上注册机)
- C# Obsolete
- win10 Administrator
- JavaScript的应用
- 实战weblogic集群之创建节点和集群
- 访问祖先类的虚方法(直接访问祖先类的VMT,但是这种方法在新版本中未必可靠)
- HDU 5933/思维
- 201521123081《Java程序设计》 第9周学习总结
- 基于Spring、SpringMVC、MyBatis、Druid、Shrio构建web系统
- linq之左连接 + group by
- nginx反向代理转发后页面上的js css文件无法加载【原创】
热门文章
- 10.cocos2d坐标系
- Atcoder AGC 019 A,B
- Dubbo简易学习
- 小米开源文件管理器MiCodeFileExplorer-源码研究(4)-文件操作工具类FileOperationHelper
- Myeclipse学习总结(2)——MyEclipse快捷键大全
- POJ——T 2796 Feel Good
- 15.Node.js REPL(交互式解释器)
- Filebeat之input和output(包含Elasticsearch Output 、Logstash Output、 Redis Output、 File Output和 Console Output)
- C#截取中英文混合字符串分行显示
- map(froeach改变值,map生成新数组)