如果有多个订阅者等待相同的承诺解决,如果已经为后来者提供了新的解决方案?
doSomething = () => {
return new Promise((resolve) => {
setTimeout(() => resolve(Math.random(), 1000)
})
}
// how to define obs?
obs.subscribe(v => console.log(v)); // 0.39458743297857473
obs.subscribe(v => console.log(v)); // 0.39458743297857473
obs.subscribe(v => console.log(v)); // 0.39458743297857473
setTimeout(() => obs.subscribe(v => console.log(v)), 2000); // 0.9485769395265746
我希望observable在第一个订阅者之前保持冷静,然后在将结果流式传输到所有后续并发订阅者之后再次冷却。我基本上不希望任何并发请求到同一个底层函数。
答案 0 :(得分:3)
doSomething = () => {
return new Promise((resolve) => {
setTimeout(() => resolve(Math.random(), 1000));
});
}
const obs = Rx.Observable
.defer(doSomething)
.share();
obs.subscribe(console.log); // resolve #1
obs.subscribe(console.log); // resolve #1
obs.subscribe(console.log); // resolve #1
setTimeout(() => obs.subscribe(console.log), 2000); // resolve #2
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>