【问题标题】:How do I use share() operator properly?如何正确使用 share() 运算符?
【发布时间】:2020-04-07 20:51:10
【问题描述】:

我有由 Rx BehaviorSubject 的 next() 方法触发的流。如何在订阅者之间共享pipedData$ 流?

我尝试在此处使用 share 运算符以避免在 map 运算符内进行大量重新计算,但没有运气 - 每个订阅者都会产生重新计算。

here's stackblitz for this issue

也可以从源获得订阅者的数量吗?

import { interval, BehaviorSubject } from 'rxjs';
import { take, map, tap, share, debounceTime } from 'rxjs/operators';

const data$ = new BehaviorSubject(null);

interval(1000).pipe(
  tap(x => console.log('emit:')),
  take(3)
).subscribe((x)=>{
  data$.next(x)
});

const pipedData$ = data$.pipe(
  debounceTime(30),
  share(),
  map(x => Math.random()),
);

console.log("--=-=-=-=--=-=----=-=-=-=-==-")
pipedData$.subscribe(x => console.log(x));
pipedData$.subscribe(x => console.log(x));
pipedData$.subscribe(x => console.log(x));

【问题讨论】:

    标签: rxjs rxjs6 reactivex


    【解决方案1】:

    看来您需要将share 移动到map 下方才能获得所需的行为。

    【讨论】:

    • 谢谢!在这个例子中,它解决了这个问题——我首先在我的项目中尝试过,这无助于以某种方式减少计算数量......将继续挖掘。有没有机会从源头获得订阅者数量?
    • 如果它继续挖掘尝试使用忽略父流的排气映射,直到完成内部流。关于订阅者数量。我没有答案,但我认为答案在共享运算符的源代码中。 github.com/ReactiveX/rxjs/blob/master/src/internal/operators/…
    • 其实是:take.ms/Vakrh 我已经创建了自己的管道运算符,并且能够找到最终订阅者的数量。
    • 更简单:就在next.source._refCount 变量take.ms/hUsdG
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2019-02-23
    • 1970-01-01
    • 2023-03-28
    • 2014-06-06
    • 2021-09-30
    相关资源
    最近更新 更多