多个订阅,无需重新计算公共部分

时间:2019-07-11 13:09:28

标签: ajax angular rxjs

const ex = ajax.getJSON('https://httpbin.org/get?a=24');
ex.pipe(pluck('args')).subscribe(x => console.log('Args: ', x));
ex.pipe(pluck('headers')).subscribe(x => console.log('Headers: ', x));
上面的

上面的代码(StackBlitz)对每个订阅发起两个ajax请求。

为所有现有订阅仅启动一个可观察管道/链的正确方法是什么?

我可以通过为ajax(StackBlitz)引入Promise来实现:

const p = new Promise(resolve => {
  ajax.getJSON('https://httpbin.org/get?a=24')
  .subscribe(res => resolve(res));
});

from(p).pipe(pluck('args')).subscribe(x => console.log('Args: ', x));
from(p).pipe(pluck('headers')).subscribe(x => console.log('Headers: ', x));

但是我相信必须有一些更方便的方法。

2 个答案:

答案 0 :(得分:4)

注释中的

shareReplay解决了我的问题:

const src = tag => of(42)
  .pipe(tap(_ => console.info(tag, 'source called')));

const ex = src('shareReplay').pipe(
  shareReplay(1)
);

ex.subscribe(x => console.log('sa:', x));
ex.subscribe(x => console.log('sb:', x));
shareReplay source called
sa: 42
sb: 42

Full demo

答案 1 :(得分:2)

您可以使用publish operator

const ex = ajax.getJSON('https://httpbin.org/get?a=24').pipe(publish());
ex.pipe(pluck('args')).subscribe(x => console.log('Args: ', x));
ex.pipe(pluck('headers')).subscribe(x => console.log('Headers: ', x));
ex.connect();

ajax请求将只发生一次,并且仅在调用connect()方法(stackblitz demo)之后发生。