Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Scoping Rx queries to the lifetime of an object.
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
public class Foo : IDisposable
{
private readonly CompositeDisposable subscriptions = new CompositeDisposable();
// Called when the object is first created; e.g., a web service response is starting or a UI Control raises its loaded event.
public void Initialize()
{
foreach (var subscription in InitializeCore())
{
subscriptions.Add(subscription);
}
}
protected virtual IEnumerable<IDisposable> InitializeCore()
{
// You could simply return Enumerable.Empty<IDisposable>() for derived types.
// Or you could yield some common queries if useful, as follows.
// SysInput depends on context; e.g., if we're defining a ViewModel, then typically it comes from ICommand or UI events.
yield return SysInput.Xs.Where(x => x % 2 == 0).Subscribe(ProcessEvenX);
yield return SysInput.Ys.Select((y, i) => Tuple.Create(y, i)).Subscribe(ProcessY);
yield return SysInput.Zs.Throttle(TimeSpan.FromSeconds(1)).Subscribe(ProcessZ);
}
protected virtual void ProcessEvenX(int x) { }
protected virtual void ProcessY(Tuple<int, int> y) { }
protected virtual void ProcessZ(object z) { }
// Called when the object is no longer needed; e.g., a web service response is canceled or a UI Control raises its Unloaded event.
public void Dispose()
{
subscriptions.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment