以下是我使用的HTML代码段:
<html>
<head>
<script src="rx.all.js"></script>
</head>
<body>
<script>
var source = new Rx.BehaviorSubject(function() {return 2;});
var stuff = source.scan([], function(val, operation) {
return operation(val);
});
stuff.subscribe(function(v) {
console.log("first subscriber");
console.log(v);
});
source.onNext(function(val) {
return val * 2;
});
stuff.subscribe(function(v) {
console.log("second subscriber");
console.log(v);
});
</script>
</body>
JS控制台中的输出是:
first subscriber
2
first subscriber
4
second subscriber
0
现在,&#34;东西&#34;进行一些处理(基本上将函数应用于当前值),这是我从TodoMVC示例中获取的ReactJs + RxJS(https://github.com/fdecampredon/react-rxjs-todomvc)的想法。
我想要实现的输出是让第二个用户也看到&#34; 4&#34;它订阅的那一刻。我将RxJS与ReactJS结合使用,因此组件在卸载时(由于路由更改)取消订阅,并在再次安装时再次订阅。
答案 0 :(得分:5)
使用replay(1)
将您的stuff
更改为热门观察者,该观察者将记住最后一个值并将其提供给后来者:
var stuff = ...;
stuff = stuff.replay(1);
// go ahead and start it listening
// you could use .refCount() here also
var subscription = stuff.connect();
// now subscribe your observers
stuff.subscribe(...);
// send some results
source.onNext(...);
source.onNext(...);
// subscribe another observer
// will see the lastest value
// as well as any new values
stuff.subscribe(...);
source.onNext(...);
// ...