这是场景:
我有多个连接到不同的数据库,我想确保代码在所有连接都处于事件状态时运行。
我正在使用 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
不会跟踪 a
和 b
的最新值,直到有订阅。
因此您可以使用不同类型的主题来跟踪最后一个值(BehaviorSubject
或 ReplaySubject
)或使用 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/