c# - FromEventPattern 如何知道事件何时完成?

标签 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 仍在等待更多事件。我如何告诉它停止等待并给我输出?

最佳答案

如果您只等待服务的单个响应,请考虑在查询表达式中使用 .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")
                );

关于c# - FromEventPattern 如何知道事件何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925538/

相关文章:

c# - 如何检查可执行文件是否与已安装的 .NET 版本兼容

c# - IEnumerable 在底层与 IObservable 有何不同?

c# - 进程外 COM 服务器

c# - 当我在 ins asp.net core 3.1 中工作时收到此错误值不能为空。 (参数 'connectionString')

c# - 从 MS Outlook 邮件中读取发件人的电子邮件地址

node.js - Redis 发布/订阅 vs Node 事件发射器

javascript - 如何避免在 React 组件中使用事件监听器无限重新渲染?

javascript - 一旦事件触发,即使我 `$.unbind(' 事件')`,所有处理程序都会触发。有没有办法防止事件处理程序在事件发生后触发?

wpf - IObservable含糊不清的引用错误

javascript - Rx debounce operator with first 和 last