Multiple subscriptions without recalculate common part

a 夏天 提交于 2019-12-13 02:53:17

问题


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));

Code above(StackBlitz) initiates two ajax requests by one for each subscription.

What is correct way to initiate only one observable pipe/chain for all existing subscriptions?

I can achieve that with introduce a Promise for ajax(StackBlitz):

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));

But I believe there must be some more convienient way.


回答1:


shareReplay from comments solves my issue:

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




回答2:


You can use the publish operator for that:

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();

The ajax request will take place just once, and only after the connect() method is called (stackblitz demo).



来源:https://stackoverflow.com/questions/56990005/multiple-subscriptions-without-recalculate-common-part

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!