RxJS处理多个数据库连接

时间:2018-01-23 17:29:37

标签: javascript asynchronous events rxjs emitter

这是情景:

我有多个连接到不同的数据库,我想确保代码在所有连接都处于活动状态时运行。

我正在使用Rxjs来处理这个问题(另一个解决方案是受欢迎的)但是我面临的问题是,如果我将其中一个连接事件组合起来后,我就永远不会进行订阅运行,因为combineLatest想要发出所有可观察数据,但是是的!



const a = new Rx.Subject();
const b = new Rx.Subject();

var bool = false;

setInterval(()=>{
    bool = !bool
    a.next(bool ? ' i am connected' : 'im NOT connected');
},1000)

setTimeout(()=>{
    b.next('i am always connected!')
},400)

// this variable will be exported to all js that run queries
var obs = new Rx.Observable.combineLatest(a,b);

setTimeout(()=>{
    obs.subscribe((andb)=>{
        console.log( andb )
        // i can check all connections at once and run the code
    })
},399)

// problem is here, i want to subscribe later than the connections 
//emit, if you edit 399 to 401 you will see that nothing is going on 

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

如果超时为399,则会在b发出之前订阅,以便您查看其值。 如果超时为401,则您会在b发出后进行订阅,因此您不会看到a的值或combineLatest,因为combineLatest需要这两者。在a订阅之前,b不会跟踪BehaviorSubjectReplaySubject的最新值。

因此,您可以使用跟踪最后一个值(repeatReplaySubject(1))的其他主题或使用const a = new Rx.Subject(); const b = new Rx.ReplaySubject(1); var bool = false; setInterval(()=>{ bool = !bool a.next(bool ? ' i am connected' : 'im NOT connected'); },1000) setTimeout(()=>{ b.next('i am always connected!') },400) // this variable will be exported to all js that run queries var obs = new Rx.Observable.combineLatest(a,b); setTimeout(()=>{ obs.subscribe((andb)=>{ console.log( andb ) // i can check all connections at once and run the code }) },401)运算符。

以下是<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>的示例(与BehaviorSubject基本相同,但不需要初始值)并在401订阅:

{{1}}
{{1}}