简体   繁体   English

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

[英]RxJS combineLatest add timer to only one observable

I have two entities, Games and Jackpots :我有两个实体, GamesJackpots
Game interface游戏界面

{
    id: string,
    name: string
}

Jackpot interface大奖界面

{
    game: string,
    amount: number
}

First I have two observables , one to get games and one to get jackpots .首先,我有两个observables ,一个用于获取游戏,一个用于获取累积奖金
And after getting the data i want to merge the data of jackpots into games based on id .在获得数据后,我想将累积奖金的数据合并到基于id游戏中。 And since the jackpots observale should get the data each seconds i used the operator timer to do so.而且由于累积奖金观察应该每秒获取数据,因此我使用操作员timer来执行此操作。 So here's my implementation:所以这是我的实现:

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) };
                })
            })
        );
    };

This implementation works fine and the data is fetched every 3 seconds.此实现工作正常,每 3 秒获取一次数据。 Now as you can see both Games and Jackpots observable get fetched every 3 seconds, My question is: is there a way to only run the Jackpots observable every 3 seconds, and exclude the Games observable from that timer.现在,您可以看到GamesJackpots observable 每 3 秒获取一次,我的问题是:有没有办法只每 3 秒运行一次Jackpots observable,并从该计时器中排除 Games observable

Context语境

combineLatest has two important properties: combineLatest有两个重要的属性:

  • it emits every time any of the Observables emits a value.每次任何 Observable 发出一个值时它都会发出。
  • it requires all source Observables to emit at least one value.它要求所有源 Observable 至少发出一个值。

Solution解决方案

You can set the timer only for the games Observable and combine it with the jackpots one.您可以仅为游戏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