如何使用GroupBy进行聚合并等待结果

本文关键字:合并 等待 结果 何使用 GroupBy | 更新日期: 2023-09-27 18:14:18

举个例子,我要记录每个球员在板球名册上走过的距离。我可能有以下对象

  • 行程(单腿)
  • 行程(距离,持续时间,球员和属于行程)
  • 球员(属于球队)
  • 团队

我想使用响应式扩展聚合这些数据。这是我的第一次尝试:

var trips = new List<Trip>();
Observable.Return( trips )
  .SelectMany( trips => trips )
  .SelectMany( trip => trip.legs )
  .GroupBy( leg => leg.player.team )
  .Select( teamLegs => {
    var teamSummary = new {
      team = teamLegs.key,
      distance = 0M,
      duration = 0M
    }
    teamLegs.Sum( x => x.distance ).Subscribe( x => { teamSummary.distance = x; } )
    teamLegs.Sum( x => x.duration ).Subscribe( x => { teamSummary.duration = x; } )
    return teamSummary;
  })
  .Select(teamSummary => {
      // If I try to do something with teamSummary.distance or duration - the above
      // sum is yet to be completed 
  })
  // ToList will make the above sums work, but only if there's only 1 Select statement above
  .ToList()
  .Subscribe(teamSummaries => {
  });

如何确保在第二个Select()语句之前完成总和?

如何使用GroupBy进行聚合并等待结果

一个可观察对象是等待的。如果您等待它,它将等待序列完成,并返回最后一项。

所以你能做的就是等待结果,而不是订阅。这样,第一个Select语句中的代码块只有在结果准备好后才会返回。

.Select(async teamLegs =>
    new {
        team = teamLegs.key,
        distance = await teamLegs.Sum(x => x.distance),
        duration = await teamLegs.Sum(x => x.duration)
        })
...

Select语句将返回IObservable<Task<(type of teamSummary)>,因此您可以使用SelectMany(...)来代替IObservable<(type of teamSummary)>