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

674 views Asked by At

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. After that I want the Sample to only give me an item on the sample interval.

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:

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...

Any ideas please?

1

There are 1 answers

0
Absolom On BEST ANSWER

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.