【发布时间】:2017-11-07 05:57:42
【问题描述】:
我正在寻找一种可观察的扩展方法来执行反向节流。我的意思是让第一个项目通过,然后在适当的时间内忽略后面的项目。
input - due time 2
|*.*.*..*..|
output
|*......*..|
请注意,这是一个与以下问题不同的问题(它们都是相同的)。下面的问题需要一个固定的抑制持续时间,而我需要一个抑制持续时间,每次新项目过早到达时都会增加抑制持续时间。下面列出的解决方案的输出可视化如下:
input - due time 2
|*.*.*..*..|
output
|*...*..*..|
- How to take first occurrence and then supress events for 2 seconds (RxJS)
- How to throttle event stream using RX?
- Rx: How can I respond immediately, and throttle subsequent requests
更新
我想出了以下解决方案,但是我对调度程序和并发性的了解不够,无法确保锁定足够好。当Scheduler参数被添加到方法中时,我也不知道如何实现这个方法。
public static IObservable<T> InverseThrottle<T>(this IObservable<T> source, TimeSpan dueTime)
{
IDisposable coolDownSupscription = null;
object subscriptionLock = new object();
return source
.Where(i =>
{
lock (subscriptionLock)
{
bool result;
if (coolDownSupscription == null)
{
result = true;
}
else
{
coolDownSupscription.Dispose();
result = false;
}
coolDownSupscription = Observable
.Interval(dueTime)
.Take(1)
.Subscribe(_ =>
{
lock (subscriptionLock)
{
coolDownSupscription = null;
}
});
return result;
}
});
}
【问题讨论】:
标签: system.reactive