Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Foo
- {
- /// <summary>
- /// An abstract base class of classes that observes one or more subject(s) by using Reactive Extensions (Rx).
- /// </summary>
- public abstract class ObserverBase : IDisposable
- {
- private IDisposable _subscription;
- /// <summary>
- /// Starts observing subject(s).
- /// </summary>
- public void StartObserving()
- {
- StopObserving(); // Ensure the previous subscription is disposed.
- _subscription = SubscribeToObservable();
- }
- /// <summary>
- /// Subscribes to observable subject(s).
- /// </summary>
- /// <returns>
- /// The subscription(s). Typically, the disposable returned from the Subscribe extension method of
- /// <seealso cref="IObservable{T}"/> should be returned.
- /// </returns>
- protected abstract IDisposable SubscribeToObservable();
- /// <summary>
- /// Stops observing the subject(s).
- /// If no subject(s) are observed currently, this method does nothing.
- /// </summary>
- public void StopObserving()
- {
- if (_subscription != null)
- {
- _subscription.Dispose();
- _subscription = null;
- }
- }
- /// <summary>
- /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- /// <summary>
- /// Releases unmanaged and - optionally - managed resources.
- /// </summary>
- /// <param name="disposing">
- /// <c>true</c> to release both managed and unmanaged resources;
- /// <c>false</c> to release only unmanaged resources.
- /// </param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- StopObserving();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement