Rx - cancellation sample

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Microsoft.Reactive.Testing;

public class Program
{
    protected static event EventHandler<EventArgs> CancelEvent;

	public static void Main()
	{
		var completed = false;

            var scheduler = new TestScheduler();
            var observable = Observable.Interval(TimeSpan.FromSeconds(1),
                                                 scheduler);

            var fromEvent = Observable.FromEventPattern<EventArgs>(p => CancelEvent += p,
                                                                   p => CancelEvent -= p,
                                                                   scheduler);

            var cancellable = observable.TakeUntil(fromEvent);

            var results = new List<long>();

            using (cancellable.Subscribe(results.Add,
										 e => { throw new Exception("No exception is planned! {0}",
																	e); },
                                         () => { completed = true; }))
            {                
                scheduler.AdvanceBy(TimeSpan.FromSeconds(3.5).Ticks);

                CancelEvent(null,
                            new EventArgs());

                scheduler.AdvanceBy(TimeSpan.FromSeconds(3).Ticks);
            }
		
			Console.WriteLine("Have I completed indeed? {0}", completed);
			Console.WriteLine("What has been registered before cancellation? {0}", string.Join(", ", results));
	}
}
;