【问题标题】:RxJs `sample` operator multiple timesRxJs `sample` 操作符多次
【发布时间】:2021-05-03 09:17:18
【问题描述】:

在 RxJS 中,当您需要组合两个 Observables 并且仅在其中一个发出时发出,您使用 withLatestFrom

source$.pipe(
  withLatestFrom(other$),
  map(([sourceValue, otherValue]) => ...) // this is only executed when `source$` has new values, regardless of `other$` emission
)

如果source$ 发出多次但other$ 没有发出,您总是得到相同的最新值并执行 执行map

如果不需要“signalling”流的值,可以使用sample

interestingStream$.pipe(
  sample(signallingStream$),
  map((interestingValue) => ...) // this function does not receive `signallingStream$`'s values
)

但是,map 仅在 signallingStream$ 发出 interestingStream$ 发出新值后才会执行;没有值向下游发出两次。

所以我的问题是,是否有一个运算符、运算符的组合或其他东西可以让我多次获得源流的最新值,而不会强迫我获取和忽略信号流的值,例如下面的sn-p?

signallingStream$.pipe(
  withLatestFrom(interestingStream$),
  map(([_ignore_, interestingValue]) => interestingValue),
)

【问题讨论】:

    标签: typescript rxjs stream observable reactivex


    【解决方案1】:

    我猜你可以使用类似下面的东西:

    const shared$ = interestingStream$.pipe(
      publishReplay(1),
    );
    
    const source = signallingStream$.pipe(
      concatMapTo(shared$.pipe(take(1))),
    );
    
    shared$.connect();
    

    publishReplay() 应该保留 ReplaySubject() 的单个实例,因此每次订阅它时,它都会从 interestingStream$ 重新发送最新值。通过调用 connect() 可以使 Observable 变得“热”。

    现场演示:https://stackblitz.com/edit/rxjs-ewew2n

    【讨论】:

      猜你喜欢
      • 2019-11-28
      • 2016-11-06
      • 2021-12-01
      • 2018-04-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 2018-06-20
      相关资源
      最近更新 更多