RxJs - 多个订阅者等待承诺的同一结果

时间:2017-02-02 22:07:14

标签: rxjs reactive-programming rxjs5

如果有多个订阅者等待相同的承诺解决,如果已经为后来者提供了新的解决方案?

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在第一个订阅者之前保持冷静,然后在将结果流式传输到所有后续并发订阅者之后再次冷却。我基本上不希望任何并发请求到同一个底层函数。

1 个答案:

答案 0 :(得分:3)

您可以使用defer作为创建运算符,然后使用share流:

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>