Christoph
Christoph

Reputation: 27985

How to use a simple timeout with Rx .NET / Dispose needed?

What is the most simple way to raise a fire and forget callback after 3 seconds with Rx .NET. I noticed this works, but do I have to dispose it or something? Im not sure.

Observable.Timer(TimeSpan.FromSeconds(3)).Subscribe(x => Console.WriteLine("Fired"));

Upvotes: 1

Views: 1380

Answers (3)

Lee Campbell
Lee Campbell

Reputation: 10783

Just curious, but your question says 'timeout', not 'timer'. What you have is an event that occurs at the given time, not a wait on an event gives up after a given time. While it seems you are happy with the answer, I thought I would check for clarity.

To do the later, you can add a .Timeout(Timespan) to an observable sequence. As James World has mentioned, there is a Scheduler at play here implicitly. While you keep the Scheduler implicit you will find unit-testing a pain. Ideally you should provide the Scheduler you want to use to the Timer/Interval/Timeout method you use.

Upvotes: 0

James World
James World

Reputation: 29776

Just for kicks, here's another alternative that uses Rx but puts the scheduler front and centre and omits the subscription business and the unnecessary argument on the Action. As before you could use the returned IDisposable to cancel the action.:

Scheduler.Default.Schedule(TimeSpan.FromSeconds(3), () => Console.WriteLine("Fired"));

Upvotes: 0

Sergey Aldoukhov
Sergey Aldoukhov

Reputation: 22744

This is it, I would mark your question as an answer if I could ;).

Regarding disposal, you usually need to dispose the subscription if:

  • you're subscribing to an observable that belongs to a container with longer life span than the subscribing component.
  • you need to "unsubscribe" early.

Your sample is not one of these, so don't worry about unsubscribing.

Upvotes: 4

Related Questions