如何对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);
这里触发的震源仅每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
如何做到这一点?
您可以使用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();
}