c# - 可观察到的 : Getting latest value in intervals until source finishes

标签 c# system.reactive

我正在寻找具有类似于此签名的可观察选择器:

static IObservable<T> TakeLatest(this IObservable<T> input, TimeSpan interval)

哪个应该:

  1. 在输入发出第一个项目时立即发出第一个项目
  2. 从那时起,在之后的固定时间间隔内,发出输入产生的最新项目
  3. 每当输入完成(或失败)时完成(或失败)

就弹珠而言,类似于以下内容 - 假设间隔 = 2 个时间单位:

<表类="s-表"> <头> 时间 <日>1 <日>2 <日>3 <日>4 <日>5 6 <日>7 <日>8 <日>9 <日>10 <日>11 <日>12 <日>13 <日>14 <日>15 <正文> 输入 一个 B C D E F(完整) 输出 一个 B D D E E 完成(F 不再发射)

是否有任何开箱即用的方法,或者一个相当简单的选择器来产生这些结果?

最佳答案

这应该完全符合您的要求。不过我还没有测试过。

/// <summary>Samples the source observable sequence at each interval,
/// allowing repeated emissions of the same element.</summary>
public static IObservable<T> SampleWithDuplicates<T>(this IObservable<T> source,
    TimeSpan interval, IScheduler scheduler = null)
{
    scheduler ??= DefaultScheduler.Instance;
    return source.Publish(published => Observable
        .Interval(interval, scheduler)
        .WithLatestFrom(published, (_, x) => x)
        .Merge(published.FirstAsync())
        .TakeUntil(published.LastOrDefaultAsync()));
}

关于c# - 可观察到的 : Getting latest value in intervals until source finishes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66710789/

相关文章:

c# - 减少不断增加的构造函数服务参数

c# - Observable 中的通知并行性

c# - 如何等待具有特定属性值的 IObservable 中的对象?

c# - 在订阅中调用 Task.Factory.StartNew(async () => {}) 通常是可疑的吗?

c# - 为什么我不需要在这个冷的 Observable 上发布?

C# 继承类列表

c# - Sveltekit + NET 6 C# Api - 登录后,我无法调用具有授权的api

c# - 如何将二维字符串数组转换为二维 [int, double, bool, ..] 数组?

c# - 将派生值作为属性公开是一种好的形式吗?

c# - 接收 : Ignoring updates caused by Subscribers