IObservable(T) Interface
TOC
Réduire la table des matières
Développer la table des matières
Cet article a fait l'objet d'une traduction automatique. Déplacez votre pointeur sur les phrases de l'article pour voir la version originale de ce texte. Informations supplémentaires.
Traduction
Source

IObservable<T>, interface

.NET Framework (current version)
 

Définit un fournisseur pour la notification de type push.

Espace de noms:   System
Assembly:  mscorlib (dans mscorlib.dll)

public interface IObservable<out T>

Paramètres de type

out T

Objet qui fournit des informations de notification.

NomDescription
System_CAPS_pubmethodSubscribe(IObserver<T>)

Notifie le fournisseur qu'un observateur doit recevoir des notifications.

The T:System.IObserver`1 and T:System.IObservable`1 interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The T:System.IObservable`1 interface represents the class that sends notifications (the provider); the T:System.IObserver`1 interface represents the class that receives them (the observer). T represents the class that provides the notification information. In some push-based notifications, the T:System.IObserver`1 implementation and T can represent the same type.

The provider must implement a single method, M:System.IObservable`1.Subscribe(System.IObserver{`0}), that indicates that an observer wants to receive push-based notifications. Callers to the method pass an instance of the observer. The method returns an T:System.IDisposable implementation that enables observers to cancel notifications at any time before the provider has stopped sending them.

At any given time, a given provider may have zero, one, or multiple observers. The provider is responsible for storing references to observers and ensuring that they are valid before it sends notifications. The T:System.IObservable`1 interface does not make any assumptions about the number of observers or the order in which notifications are sent.

The provider sends the following three kinds of notifications to the observer by calling T:System.IObserver`1 methods:

  • The current data. The provider can call the M:System.IObserver`1.OnNext(`0) method to pass the observer a T object that has current data, changed data, or fresh data.

  • An error condition. The provider can call the M:System.IObserver`1.OnError(System.Exception) method to notify the observer that some error condition has occurred.

  • No further data. The provider can call the M:System.IObserver`1.OnCompleted method to notify the observer that it has finished sending notifications.

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 LocationTracker class provides the T:System.IObservable`1 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 M:System.IObserver`1.OnNext(`0) 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 LocationUnknownException object, which is shown in the following example. It then calls each observer's M:System.IObserver`1.OnError(System.Exception) method and passes it the LocationUnknownException object. Note that LocationUnknownException derives from T:System.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 M:System.IObservable`1.Subscribe(System.IObserver{`0}) method, which assigns a reference to the observer object to a private generic T:System.Collections.Generic.List`1 object. The method returns an Unsubscriber object, which is an T:System.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 M:System.IObserver`1.OnCompleted method and then clears the internal list of observers.

In this example, the LocationReporter class provides the T:System.IObserver`1 implementation. It displays information about the current location to the console. Its constructor includes a name parameter, which enables the LocationReporter instance to identify itself in its string output. It also includes a Subscribe method, which wraps a call to the provider's M:System.IObservable`1.Subscribe(System.IObserver{`0}) method. This allows the method to assign the returned T:System.IDisposable reference to a private variable. The LocationReporter class also includes an Unsubscribe method, which calls the M:System.IDisposable.Dispose method of the object that is returned by the M:System.IObservable`1.Subscribe(System.IObserver{`0}) 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 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.

Universal Windows Platform
Disponible depuis 4.5
.NET Framework
Disponible depuis 4.0
Portable Class Library
Pris en charge dans : portable .NET platforms
Windows Phone Silverlight
Disponible depuis 7.0
Windows Phone
Disponible depuis 8.1
Retour au début
Afficher:
© 2016 Microsoft