Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dispose of an observable after a set time?

I have an observable that is sending data at a fixed rate every 2 seconds to some observer. I want a way that after 2 minutes has elapsed, the observable that is sending the data will dispose of itself after telling the subject that it completed. I'm using 2 timers one for emitting data for the 2 second intervals and another for the total 2 min duration so it can send the OnComplete. I was wondering if there's a way to also dispose itself after the 2 minutes has completed using the timer?

my code looks something like this:

Observable.Create<>(
    observer =>
    {
        var timer = new Timer();
        timer.Elapsed += (s, e) => observer.OnNext( *send some string* );
        timer.start();
        return Disposable.Empty;
    }
)
like image 260
Armagetin Avatar asked Sep 19 '16 23:09

Armagetin


1 Answers

It's really rather simple. Just do this:

Observable
    .Interval(TimeSpan.FromSeconds(2.0))
    .TakeUntil(Observable.Timer(TimeSpan.FromMinutes(2.0)))
    .Subscribe(x =>
    {
    });

This will automatically end the observable after 2 minutes and do all the unsubscribing for you.

like image 195
Enigmativity Avatar answered Nov 07 '22 21:11

Enigmativity