2

比如说,我正在跟踪每个球员为获得板球名单所走过的距离。我可能有以下对象

  • 旅行(IList 腿)
  • 腿(距离、持续时间、玩家和所属行程)
  • 球员(属于球队)
  • 团队

我想使用 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() 语句之前完成总和?

4

1 回答 1

1

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

所以你可以做的是等待结果,而不是订阅。这样,第一个 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)>.

于 2019-07-12T11:07:32.257 回答