加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 具有Reactive Extensions的组的缓冲区组,嵌套订阅

发布时间:2020-12-15 23:37:59 所属栏目:百科 来源:网络整理
导读:我有一个事件源,生成属于某些组的事件.我想缓冲这些组并将组(分批)发送到存储.到目前为止我有这个: eventSource .GroupBy(event = event.GroupingKey) .Select(group = new { group.Key,Events = group }) .Subscribe(group = group.Events .Buffer(TimeSpa
我有一个事件源,生成属于某些组的事件.我想缓冲这些组并将组(分批)发送到存储.到目前为止我有这个:

eventSource
    .GroupBy(event => event.GroupingKey)
    .Select(group => new { group.Key,Events = group })
    .Subscribe(group => group.Events
                            .Buffer(TimeSpan.FromSeconds(60),100)
                            .Subscribe(list => SendToStorage(list)));

所以有一个嵌套订阅组中的事件.不知怎的,我认为有更好的方法,但我还没有弄清楚.

解决方法

这是解决方案:

eventSource
    .GroupBy(e => e.GroupingKey)
    .SelectMany(group => group.Buffer(TimeSpan.FromSeconds(60),100))
    .Subscribe(list => SendToStorage(list));

这里有一些可以帮助你’减少’的一般规则:

1)嵌套订阅通常通过在嵌套订阅之前选择所有内容然后是合并,然后是嵌套订阅来修复.所以应用它,你得到这个:

eventSource
    .GroupBy(e => e.GroupingKey)
    .Select(group => new { group.Key,Events = group })
    .Select(group => group.Events.Buffer(TimeSpan.FromSeconds(60),100)) //outer subscription selector
    .Merge()
    .Subscribe(list => SendToStorage(list));

2)你显然可以组合两个连续的选择(因为你没有对匿名对象做任何事情,可以删除它):

eventSource
    .GroupBy(e => e.GroupingKey)
    .Select(group => group.Buffer(TimeSpan.FromSeconds(60),100)) 
    .Merge()
    .Subscribe(list => SendToStorage(list));

3)最后,Select和后面的Merge可以简化为SelectMany:

eventSource
    .GroupBy(e => e.GroupingKey)
    .SelectMany(group => group.Buffer(TimeSpan.FromSeconds(60),100))
    .Subscribe(list => SendToStorage(list));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读