我正在寻找具有类似于此签名的可观察选择器:
static IObservable<T> TakeLatest(this IObservable<T> input, TimeSpan interval)
哪个应该:
- 在输入发出第一个项目时立即发出第一个项目
- 从那时起,在之后的固定时间间隔内,发出输入产生的最新项目
- 每当输入完成(或失败)时完成(或失败)
就弹珠而言,类似于以下内容 - 假设间隔 = 2 个时间单位:
是否有任何开箱即用的方法,或者一个相当简单的选择器来产生这些结果?
最佳答案
这应该完全符合您的要求。不过我还没有测试过。
/// <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/