[英]Rx take first element and skip following elements for an interval of time
I try to access a stream every 2 seconds and get the first value within this time. 我尝试每2秒访问一次流,并在此时间内获得第一个值。 Example:
例:
Values: -1--2-3---4-----5--6-7--8
Result: -1-------3--------5------
I tried the code like int this thread (quite similar problem): 我尝试了类似int 这个线程的代码(相当类似的问题):
subject.AsObservable().Window(TimeSpan.FromSeconds(2))
.SelectMany(f => f.Take(1))
.Subscribe(f =>
{
Console.WriteLine("Counter: " + counter + " Time:" + DateTime.Now.Millisecond);
counter++;
});
However, the 2 seconds do not work, the counter updates too fast even after 200 milliseconds. 但是,这2秒不起作用,即使200毫秒后,计数器的更新速度仍然过快。
What am I missing? 我想念什么?
Data are added to the subject by using this code: 使用以下代码将数据添加到主题:
Task.Run(async () =>
{
while (await call.ResponseStream.MoveNext(default(CancellationToken)))
{
foreach (var result in call.ResponseStream.Current.Results)
{
subject.OnNext(result);
}
}
});
Your query seems to be perfectly fine. 您的查询似乎很好。 Let's test this by giving it a good set of source data:
让我们通过提供一组良好的源数据来进行测试:
var rnd = new Random();
var source =
Observable
.Generate(0, x => true, x => x + 1, x => x,
x => TimeSpan.FromSeconds(rnd.NextDouble() / 10.0));
This is going to produce a value every 0.0 to 100.0 milliseconds. 这将每0.0到100.0毫秒产生一个值。 So if the query is correct we should expect to see a value produced within 100 milliseconds of each 2,0 second window (give or take Windows OS timing issues).
因此,如果查询正确,我们应该期望在每个2.0秒窗口的100毫秒内看到一个值(给出或考虑Windows操作系统计时问题)。
Here's a slightly better version of the subscription of the query: 这是查询订阅的稍好版本:
var sw = Stopwatch.StartNew();
source
.Window(TimeSpan.FromSeconds(2.0))
.SelectMany(f => f.Take(1))
.Subscribe(f =>
{
Console.WriteLine($"Counter: {f} Time: {sw.Elapsed.TotalMilliseconds}");
});
These results I get are like: 我得到的这些结果是:
Counter: 0 Time: 110.8073 Counter: 33 Time: 2124.7605 Counter: 67 Time: 4061.8636 Counter: 101 Time: 6061.1922 Counter: 134 Time: 8090.158 Counter: 169 Time: 10173.0396 Counter: 197 Time: 12153.0229 Counter: 233 Time: 14138.7718 Counter: 265 Time: 16144.8861 Counter: 296 Time: 18122.042 Counter: 337 Time: 20141.1837 Counter: 373 Time: 22115.0944 Counter: 410 Time: 24162.0706
It has a bit of timer drift, but it's following the expected pattern. 它有一些计时器漂移,但是遵循预期的模式。 The query works.
查询有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.