FromEventPattern如何知道事件何时完成?

时间:2013-07-29 13:36:04

标签: c# events system.reactive

我有一个可观察的集合,它由大量事件填充。我想从EventArg中获取信息,按名称对其进行分组,然后选择每个名称的最大日期。我试过这个:

_subscription = Observable
            .FromEventPattern<NewLoanEventHandler, NewLoanEventArgs>(
                h => loan.NewLoanEvent += h, 
                h => loan.NewLoanEvent -= h)
            .Select(a => a.EventArgs.Counterpatry)
            .GroupBy(c => c.Name)
            .SelectMany(grp => grp.Max( c => c.MaturityDate ).Select( maturity => new {grp.Key, maturity}) )
            .Subscribe( 
                i => Console.WriteLine("{0} --> {1}", i.Key, i.maturity),
                Console.WriteLine,
                () => Console.WriteLine("completed")
                );

我认为它可能会做我想要的,但订阅永远不会完成:我从来没有得到完整的消息,我没有得到任何输出。也就是说,我怀疑,因为Observable仍在等待更多事件。我怎么告诉它停止等待并给我输出?

1 个答案:

答案 0 :(得分:4)

如果您只是等待服务的单个响应,请考虑在查询表达式中使用.Take(1)或.FirstAsync():

_subscription = Observable
            .FromEventPattern<NewLoanEventHandler, NewLoanEventArgs>(
                h => loan.NewLoanEvent += h, 
                h => loan.NewLoanEvent -= h)
            .Take(1)
            .Select(a => a.EventArgs.Counterpatry)
            .GroupBy(c => c.Name)
            .SelectMany(grp => grp.Max( c => c.MaturityDate ).Select( maturity => new {grp.Key, maturity}) )
            .Subscribe( 
                i => Console.WriteLine("{0} --> {1}", i.Key, i.maturity),
                Console.WriteLine,
                () => Console.WriteLine("completed")
                );