Created
November 10, 2014 12:01
-
-
Save RxDave/39b7eeff79b57761b14a to your computer and use it in GitHub Desktop.
Scoping Rx queries to the lifetime of an object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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