2

I am replacing timers on rx's Observable.Interval and I encountered a problem. I don't know how to pause such timer. I don't mean pause subscription, but pausing and resuming time counting. I know how to do this in dirty way, but I would like know maybe nicer solution.

My current code:

var RemainingTimes = Observable
            .Interval(TimeSpan.FromMilliseconds(refreshInterval))
            .Select(t => _provider.Duration - TimeSpan.FromMilliseconds(t * refreshInterval))
Lukas
  • 621
  • 2
  • 12
  • 29

1 Answers1

6

Would doing this work for you?

var pause = false;
var RemainingTimes =
    Observable
        .Interval(TimeSpan.FromMilliseconds(refreshInterval))
        .Where(x => pause == false)
        .Select(t => _provider.Duration - TimeSpan.FromMilliseconds(t * refreshInterval));

You then just change pause = true and pause = false to turn it off an on.

If you want to actually start and stop the timer, without resubscribing, then this is a way to go:

var pauser = new Subject<bool>();
var RemainingTimes =
    pauser
        .StartWith(true)
        .Select(b => b
            ? Observable.Empty<DateTime>()
            : Observable
                .Interval(TimeSpan.FromMilliseconds(refreshInterval))
                .Select(t => _provider.Duration - TimeSpan.FromMilliseconds(t * refreshInterval)))
        .Switch();

Then just call pauser.OnNext(true) and pauser.OnNext(false) to stop and start.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Second code works almost good, but it doesn't restore time before pause after resuming timer. – Lukas Feb 21 '16 at 12:22
  • @Lukas - What do you mean by "doesn't restore the time"? – Enigmativity Feb 21 '16 at 21:22
  • I mean: timer starts ticking 10 minutes remaining, user pauses it at 5minutes remaining, timer stops ticking, later it is resumed and timer should start ticking not from 10 minutes, but from 5minutes. – Lukas Feb 22 '16 at 08:20
  • @Lukas - That's a tricky requirement. I'll have a think about it. – Enigmativity Feb 22 '16 at 10:59