Using C# with Rx.NET. Is there a way to extend the duration time of an Observable.Timer
after it was started? Is there a way with Join(...)
or Expand(...)
? I do not like to dispose the old timer and not like to create a new one.
Example: initial duration is 5 minutes. But 1 minute before the timer completes, I like to reset it to 5 minutes, to measure 5 minutes again.
var _timerDisposable = Observable.Timer(duration)
.ObserveOn(Scheduler.Default)
.Subscribe((_) => DoSomething());
This is similar to @Krzystztof's answer, but more idiomatic to Rx:
var DoSomething = new Action(() => {});
var duration = TimeSpan.FromSeconds(5);
var resetSignal = new Subject<Unit>();
var scheduler = Scheduler.Default;
resetSignal
.Select(_ => Observable.Timer(duration))
.Switch()
.ObserveOn(scheduler)
.Subscribe(_ => DoSomething())
// to reset or start timer:
resetSignal.OnNext(Unit.Default);
Explanation:
Every time resetSignal
produces a value, a new Timer
is started. Next, the Switch
operator automatically switches to the latest observable (in our case the latest timer), effectively ignoring old ones, when a new one pops out. Under the covers, Switch
cleanly disposes the old subscription to the previous observable (timer), and subscribes to the new observable.
The correct action here is to dispose of the subscription, then create a new observable sequence. By disposing, you will unsubscribe from the timer and will not receive a notification when the duration has expired. Note that it is unnecessary to indicate the default scheduler.
_timerSubscription.Dispose();
_timerSubscription = Observable.Timer(duration)
.Subscribe((_) => DoSomething());
--
Editorial: There are many ways to do what you ask. Since there's no broader context presented, this is probably the simplest way. Approaches suggested by others, while technically correct, may be confusing and hard to interpret, but may also work better in your use case. In the future, a more complete example or description of the issue may yield better results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With