3

以下是我用作示例的 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 

现在,“stuff”进行了一些处理(基本上将函数应用于当前值),这是我从 ReactJs + RxJS 的 TodoMVC 示例(https://github.com/fdecampredon/react-rxjs-todomvc)中获得的想法.

我试图实现的输出是让第二个订阅者在订阅的那一刻也看到“4”。我将 RxJS 与 ReactJS 结合使用,因此组件在卸载时取消订阅(由于路由更改),并在再次安装时再次订阅。

4

1 回答 1

4

用于将您的值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(...);
// ...
于 2014-09-15T14:31:04.207 回答