繁体   English   中英

RxJS combineLatest 仅将计时器添加到一个可观察对象

[英]RxJS combineLatest add timer to only one observable

我有两个实体, GamesJackpots
游戏界面

{
    id: string,
    name: string
}

大奖界面

{
    game: string,
    amount: number
}

首先,我有两个observables ,一个用于获取游戏,一个用于获取累积奖金
在获得数据后,我想将累积奖金的数据合并到基于id游戏中。 而且由于累积奖金观察应该每秒获取数据,因此我使用操作员timer来执行此操作。 所以这是我的实现:

private getGames = (category: string): Observable<IGame[]> => {
        return timer(0, 3000).pipe(
            mergeMap(() => combineLatest([this.gameService.getGames(), this.gameService.getJackpots()])),
            map(([games, jackpots]) => {
                return games?.filter(game => game?.categories?.includes(category))?.map(game => {
                    return { ...game, jackpot: jackpots?.find(jackpot => jackpot?.game === game?.id) };
                })
            })
        );
    };

此实现工作正常,每 3 秒获取一次数据。 现在,您可以看到GamesJackpots observable 每 3 秒获取一次,我的问题是:有没有办法只每 3 秒运行一次Jackpots observable,并从该计时器中排除 Games observable

语境

combineLatest有两个重要的属性:

  • 每次任何 Observable 发出一个值时它都会发出。
  • 它要求所有源 Observable 至少发出一个值。

解决方案

您可以仅为游戏Observable 设置timer ,并将其与累积奖金之一相结合。

private getGames = (category: string): Observable<IGame[]> => {
  return combineLatest([
    timer(0, 3000).pipe(mergeMap(() => this.gameService.getGames())),
    this.gameService.getJackpots(),
  ]).pipe(
    map(([games, jackpots]) => {
      return games
        ?.filter((game) => game?.categories?.includes(category))
        ?.map((game) => {
          return { ...game, jackpot: jackpots?.find((jackpot) => jackpot?.game === game?.id) };
        });
    })
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM