簡體   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