简体   繁体   English

如何创建一个 Rx observable 来获取即时值然后采样?

[英]How do I create an Rx observable that gets an immediate value and then samples?

I want to use Sample to reduce the frequency of items coming out of my observable, but I want to immediately see the first event go through without being held up for the sample duration.我想使用 Sample 来减少从我的 observable 中出现的项目的频率,但我想立即看到第一个事件通过而不会在样本持续时间内被阻止。 After that I want the Sample to only give me an item on the sample interval.之后,我希望 Sample 只给我一个关于采样间隔的项目。

The code I have for the simple Sample is:我对简单示例的代码是:

var sampler = Observable
        .Interval(TimeSpan.FromSeconds(2))
        .Select(_ => Unit.Default);

var seq = Observable.FromEventPattern<IntEventArgs>(h => _eventSource.Happened += h, h => _eventSource.Happened -= h)
        .Sample(sampler);

So I tried to use this to make it produce an item immediately, however that stops the observable working altogether:所以我试图用它来让它立即产生一个项目,但是这完全停止了可观察的工作:

var seq = Observable.FromEventPattern<IntEventArgs>(h => _eventSource.Happened += h, h => _eventSource.Happened -= h)
        .Sample(Observable.Return(Unit.Default).Concat(sampler));

Then I thought maybe the problem is the Unit.Default part of the sampler so I tried getting rid of that but now that gives a compiler error:然后我想问题可能出在采样器的 Unit.Default 部分,所以我尝试摆脱它,但现在给出了编译器错误:

var sampler = Observable
        .Interval(TimeSpan.FromSeconds(2));

var seq = Observable.FromEventPattern<IntEventArgs>(h => _eventSource.Happened += h, h => _eventSource.Happened -= h)
        .Observable.Return(Unit.Default).Concat(sampler);

I've tried googling for things like "c# immediate observable sample" but nothing shows up, I guess I'm using the wrong terminology but not sure what I do need...我试过在谷歌上搜索“c#即时可观察样本”之类的东西,但没有显示任何内容,我想我使用了错误的术语但不确定我需要什么......

Any ideas please?请问有什么想法吗?

Does this work for you?这对你有用吗?

var observable = Observable.Merge<IntEventArgs>(h => _eventSource.Happened += h, 
                                                h => _eventSource.Happened -= h)
                           .Publish()
                           .RefCount();

var seq = Observable.Merge<IntEventArgs>(observable.FirstAsync(),
                                         observable.Skip(1).Sample(sampler));

The Publish() method makes sure that you register only once to your event. Publish() 方法确保您只向事件注册一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM