javascript – RxJS将当前值推送给后期订阅者

以下是我使用的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”进行了一些处理(基本上将函数应用于当前值),这是我从TodoMVC示例中获取的ReactJs RxJS(https://github.com/fdecampredon/react-rxjs-todomvc)的想法.

我想要实现的输出是让第二个用户在订阅时也看到“4”.我正在将RxJS与ReactJS结合使用,因此组件在卸载时会取消订阅(由于路由更改),并在再次安装时再次订阅.

解决方法:

使用replay(1)将你的东西变成一个热门观察者,它将记住最后一个值并将其提供给后来者:

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(...);
// ...
上一篇:javascript – Angular 5 [隐藏]没有完全正常工作


下一篇:javascript – 用observable替换回调地狱