如何聚合 GroupBy 并等待结果

How to Aggregate with GroupBy and wait for results

举例来说,我正在跟踪板球名册上每个球员走过的距离。我可能有以下对象

我想使用 Reactive Extensions 聚合这些数据。这是我的第一次尝试:

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() 语句之前完成?

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

所以你能做的就是等待结果,而不是订阅。 这样,一旦结果准备就绪,第一个 Select 内的块将仅 return。

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

Select 语句将 return IObservable<Task<(type of teamSummary)> 因此您可以使用 SelectMany(...) 来获取 IObservable<(type of teamSummary)>.