问题
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