javascript - RxJS 处理多个数据库连接

标签 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>

最佳答案

您在 b 发出之前订阅超时 399,以便您看到它的值。 超时 401 您在 b 发出后订阅,因此您看不到它的值或 a 的值,因为 combineLatest 需要两者。 combineLatest 不会跟踪 ab 的最新值,直到有订阅。

因此您可以使用不同类型的主题来跟踪最后一个值(BehaviorSubjectReplaySubject)或使用 repeat 运算符。

这是一个使用 ReplaySubject(1) 的示例(与 BehaviorSubject 基本相同,但不需要初始值)并在 401 订阅:

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>

关于javascript - RxJS 处理多个数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407583/

相关文章:

javascript - 当我的动画完成时,transitionend 事件不会触发

java - Android PhoneGap 1.7 调用 javascript 函数

javascript - 网络音频API : discover a node's connections

javascript - 当动态添加输入字段且 ajax 不起作用时,JQuery 单击“浏览”

javascript - 如何区分通过鼠标滚动和在 JavaScript 中以编程方式滚动?

c# - 如何 async-await "save threads"?

objective-c - 如何让 MainThread 等到某些异步操作完成?

javascript - 检索 Firebase 数据并返回它的最佳方式,或其他方式

c# - 将事件处理程序附加到动态 com 对象

java - 通过外部事件退出 while 循环