Advertisement
atsukanrock

Thin wrapper for Rx's observer

Jul 16th, 2014
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Foo
  4. {
  5.     /// <summary>
  6.     /// An abstract base class of classes that observes one or more subject(s) by using Reactive Extensions (Rx).
  7.     /// </summary>
  8.     public abstract class ObserverBase : IDisposable
  9.     {
  10.         private IDisposable _subscription;
  11.  
  12.         /// <summary>
  13.         /// Starts observing subject(s).
  14.         /// </summary>
  15.         public void StartObserving()
  16.         {
  17.             StopObserving(); // Ensure the previous subscription is disposed.
  18.  
  19.             _subscription = SubscribeToObservable();
  20.         }
  21.  
  22.         /// <summary>
  23.         /// Subscribes to observable subject(s).
  24.         /// </summary>
  25.         /// <returns>
  26.         /// The subscription(s). Typically, the disposable returned from the Subscribe extension method of
  27.         /// <seealso cref="IObservable{T}"/> should be returned.
  28.         /// </returns>
  29.         protected abstract IDisposable SubscribeToObservable();
  30.  
  31.         /// <summary>
  32.         /// Stops observing the subject(s).
  33.         /// If no subject(s) are observed currently, this method does nothing.
  34.         /// </summary>
  35.         public void StopObserving()
  36.         {
  37.             if (_subscription != null)
  38.             {
  39.                 _subscription.Dispose();
  40.                 _subscription = null;
  41.             }
  42.         }
  43.  
  44.         /// <summary>
  45.         /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  46.         /// </summary>
  47.         public void Dispose()
  48.         {
  49.             Dispose(true);
  50.             GC.SuppressFinalize(this);
  51.         }
  52.  
  53.         /// <summary>
  54.         /// Releases unmanaged and - optionally - managed resources.
  55.         /// </summary>
  56.         /// <param name="disposing">
  57.         /// <c>true</c> to release both managed and unmanaged resources;
  58.         /// <c>false</c> to release only unmanaged resources.
  59.         /// </param>
  60.         protected virtual void Dispose(bool disposing)
  61.         {
  62.             if (disposing)
  63.             {
  64.                 StopObserving();
  65.             }
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement