上采样序列

时间:2013-02-12 11:32:39

标签: c# system.reactive

RX序列如何上采样,即更频繁地触发?

.Sample运算符仅允许下采样:

IObservable<long> source = Observable.Interval(TimeSpan.FromMilliseconds(5000));
IObservable<long> trigger = Observable.Interval(TimeSpan.FromMilliseconds(1000));

//var triggeredSource = source.Sample(trigger);
var triggeredSource = source.Sample(TimeSpan.FromMilliseconds(1000)); 

source.Subscribe(Console.WriteLine);
triggeredSource.Subscribe(Console.WriteLine);

这里的triggeredSource每隔5000毫秒而不是1000毫秒才会触发。我们想要:

source:  ----a----b----c----d------
trigger: -o-o-o-o-o-o-o-o-o-o-o-o-o
result:  ----aa-a-b-b-bcc-c-d-d-d-d

如何做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用CombineLatest获得所需的行为 - 从概念上讲,它是Get Last Value加上Merge

[编辑:发布后才发现你在评论中提到这一点 - 它可能是你获得的最“有效”的方式]

IObservable<long> source = Observable.Interval(TimeSpan.FromMilliseconds(500));
IObservable<long> trigger = Observable.Interval(TimeSpan.FromMilliseconds(100));

var triggeredSource = source.CombineLatest(trigger, (src, trig) => src);

using(triggeredSource.Subscribe(Console.WriteLine))
{
    Console.ReadLine();
}