Lire en anglais Modifier

Partager via


IObserver<T> Interface

Definition

Provides a mechanism for receiving push-based notifications.

public interface IObserver<in T>

Type Parameters

T

The object that provides notification information.

This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.
Derived

Examples

The following example illustrates the observer design pattern. It defines a Location class that contains latitude and longitude information.

public struct Location
{
   double lat, lon;

   public Location(double latitude, double longitude)
   {
      this.lat = latitude;
      this.lon = longitude;
   }

   public double Latitude
   { get { return this.lat; } }

   public double Longitude
   { get { return this.lon; } }
}

The LocationReporter class provides the IObserver<T> implementation. It displays information about the current location to the console. Its constructor includes a name parameter, which allows the LocationReporter instance to identify itself in its string output. It also includes a Subscribe method, which wraps a call to the provider's Subscribe method. This enables the method to assign the returned IDisposable reference to a private variable. The LocationReporter class also includes an Unsubscribe method, which calls the IDisposable.Dispose method of the object returned by the IObservable<T>.Subscribe method. The following code defines the LocationReporter class.

using System;

public class LocationReporter : IObserver<Location>
{
   private IDisposable unsubscriber;
   private string instName;

   public LocationReporter(string name)
   {
      this.instName = name;
   }

   public string Name
   {  get{ return this.instName; } }

   public virtual void Subscribe(IObservable<Location> provider)
   {
      if (provider != null)
         unsubscriber = provider.Subscribe(this);
   }

   public virtual void OnCompleted()
   {
      Console.WriteLine("The Location Tracker has completed transmitting data to {0}.", this.Name);
      this.Unsubscribe();
   }

   public virtual void OnError(Exception e)
   {
      Console.WriteLine("{0}: The location cannot be determined.", this.Name);
   }

   public virtual void OnNext(Location value)
   {
      Console.WriteLine("{2}: The current location is {0}, {1}", value.Latitude, value.Longitude, this.Name);
   }

   public virtual void Unsubscribe()
   {
      unsubscriber.Dispose();
   }
}

The LocationTracker class provides the IObservable<T> implementation. Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. If the Location value is not null, the TrackLocation method calls the OnNext method of each observer.

public class LocationTracker : IObservable<Location>
{
   public LocationTracker()
   {
      observers = new List<IObserver<Location>>();
   }

   private List<IObserver<Location>> observers;

   public IDisposable Subscribe(IObserver<Location> observer)
   {
      if (!observers.Contains(observer))
         observers.Add(observer);
      return new Unsubscriber(observers, observer);
   }

   private class Unsubscriber : IDisposable
   {
      private List<IObserver<Location>>_observers;
      private IObserver<Location> _observer;

      public Unsubscriber(List<IObserver<Location>> observers, IObserver<Location> observer)
      {
         this._observers = observers;
         this._observer = observer;
      }

      public void Dispose()
      {
         if (_observer != null && _observers.Contains(_observer))
            _observers.Remove(_observer);
      }
   }

   public void TrackLocation(Nullable<Location> loc)
   {
      foreach (var observer in observers) {
         if (!loc.HasValue)
            observer.OnError(new LocationUnknownException());
         else
            observer.OnNext(loc.Value);
      }
   }

   public void EndTransmission()
   {
      foreach (var observer in observers.ToArray())
         if (observers.Contains(observer))
            observer.OnCompleted();

      observers.Clear();
   }
}

If the Location value is null, the TrackLocation method instantiates a LocationNotFoundException object, which is shown in the following example. It then calls each observer's OnError method and passes it the LocationNotFoundException object. Note that LocationNotFoundException derives from Exception but does not add any new members.

public class LocationUnknownException : Exception
{
   internal LocationUnknownException()
   { }
}

Observers register to receive notifications from a TrackLocation object by calling its IObservable<T>.Subscribe method, which assigns a reference to the observer object to a private generic List<T> object. The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. The LocationTracker class also includes an EndTransmission method. When no further location data is available, the method calls each observer's OnCompleted method and then clears the internal list of observers.

The following code then instantiates the provider and the observer.

using System;

class Program
{
   static void Main(string[] args)
   {
      // Define a provider and two observers.
      LocationTracker provider = new LocationTracker();
      LocationReporter reporter1 = new LocationReporter("FixedGPS");
      reporter1.Subscribe(provider);
      LocationReporter reporter2 = new LocationReporter("MobileGPS");
      reporter2.Subscribe(provider);

      provider.TrackLocation(new Location(47.6456, -122.1312));
      reporter1.Unsubscribe();
      provider.TrackLocation(new Location(47.6677, -122.1199));
      provider.TrackLocation(null);
      provider.EndTransmission();
   }
}
// The example displays output similar to the following:
//      FixedGPS: The current location is 47.6456, -122.1312
//      MobileGPS: The current location is 47.6456, -122.1312
//      MobileGPS: The current location is 47.6677, -122.1199
//      MobileGPS: The location cannot be determined.
//      The Location Tracker has completed transmitting data to MobileGPS.

Remarks

The IObserver<T> and IObservable<T> interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The IObservable<T> interface represents the class that sends notifications (the provider); the IObserver<T> interface represents the class that receives them (the observer). T represents the class that provides the notification information.

An IObserver<T> implementation arranges to receive notifications from a provider (an IObservable<T> implementation) by passing an instance of itself to the provider's IObservable<T>.Subscribe method. This method returns an IDisposable object that can be used to unsubscribe the observer before the provider finishes sending notifications.

The IObserver<T> interface defines the following three methods that the observer must implement:

  • The OnNext method, which is typically called by the provider to supply the observer with new data or state information.

  • The OnError method, which is typically called by the provider to indicate that data is unavailable, inaccessible, or corrupted, or that the provider has experienced some other error condition.

  • The OnCompleted method, which is typically called by the provider to indicate that it has finished sending notifications to observers.

Methods

OnCompleted()

Notifies the observer that the provider has finished sending push-based notifications.

OnError(Exception)

Notifies the observer that the provider has experienced an error condition.

OnNext(T)

Provides the observer with new data.

Applies to

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also