本文介绍了多个订阅,无需重新计算公共部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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请求.

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?

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

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.

推荐答案

shareReplay 通过评论解决了我的问题:

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

完整演示

这篇关于多个订阅,无需重新计算公共部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:09