IObserver<T> Interface

Définition

Fournit un mécanisme pour recevoir des notifications de type push.Provides a mechanism for receiving push-based notifications.

generic <typename T>
public interface class IObserver
public interface IObserver<in T>
type IObserver<'T> = interface
Public Interface IObserver(Of In T)

Paramètres de type

T

Objet qui fournit des informations de notification.The object that provides notification information.

Ce paramètre de type est contravariant. Cela signifie que vous pouvez utiliser le type spécifié ou tout type moins dérivé. Pour plus d’informations sur la covariance et la contravariance, consultez Covariance et contravariance dans les génériques.
Dérivé

Exemples

L’exemple suivant illustre le modèle de conception observateur.The following example illustrates the observer design pattern. Il définit une Location classe qui contient des informations de latitude et de longitude.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; } }
}
Public Structure Location
   Dim lat, lon As Double

   Public Sub New(ByVal latitude As Double, ByVal longitude As Double)
      Me.lat = latitude
      Me.lon = longitude
   End Sub

   Public ReadOnly Property Latitude As Double
      Get
         Return Me.lat
      End Get
   End Property

   Public ReadOnly Property Longitude As Double
      Get
         Return Me.lon
      End Get
   End Property
End Structure

La LocationReporter classe fournit l' IObserver<T> implémentation de.The LocationReporter class provides the IObserver<T> implementation. Il affiche des informations sur l’emplacement actuel de la console.It displays information about the current location to the console. Son constructeur comprend un name paramètre qui permet à l' LocationReporter instance de s’identifier dans sa sortie de chaîne.Its constructor includes a name parameter, which allows the LocationReporter instance to identify itself in its string output. Elle inclut également une Subscribe méthode qui encapsule un appel à la méthode du fournisseur Subscribe .It also includes a Subscribe method, which wraps a call to the provider's Subscribe method. Cela permet à la méthode d’assigner la référence retournée IDisposable à une variable privée.This enables the method to assign the returned IDisposable reference to a private variable. La LocationReporter classe comprend également une Unsubscribe méthode, qui appelle la IDisposable.Dispose méthode de l’objet retourné par la IObservable<T>.Subscribe méthode.The LocationReporter class also includes an Unsubscribe method, which calls the IDisposable.Dispose method of the object returned by the IObservable<T>.Subscribe method. Le code suivant définit la LocationReporter classe.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();
   }
}
Public Class LocationReporter : Implements IObserver(Of Location)
   Dim unsubscriber As IDisposable
   Dim instName As String

   Public Sub New(ByVal name As String)
      Me.instName = name
   End Sub

   Public ReadOnly Property Name As String
      Get
         Return instName
      End Get
   End Property

   Public Overridable Sub Subscribe(ByVal provider As IObservable(Of Location))
      If provider Is Nothing Then Exit Sub
      unsubscriber = provider.Subscribe(Me)
   End Sub

   Public Overridable Sub OnCompleted() Implements System.IObserver(Of Location).OnCompleted
      Console.WriteLine("The Location Tracker has completed transmitting data to {0}.", Me.Name)
      Me.Unsubscribe()
   End Sub

   Public Overridable Sub OnError(ByVal e As System.Exception) Implements System.IObserver(Of Location).OnError
      Console.WriteLine("{0}: The location cannot be determined.", Me.Name)
   End Sub

   Public Overridable Sub OnNext(ByVal value As Location) Implements System.IObserver(Of Location).OnNext
      Console.WriteLine("{2}: The current location is {0}, {1}", value.Latitude, value.Longitude, Me.Name)
   End Sub

   Public Overridable Sub Unsubscribe()
      unsubscriber.Dispose()
   End Sub
End Class

La LocationTracker classe fournit l' IObservable<T> implémentation de.The LocationTracker class provides the IObservable<T> implementation. TrackLocationLa méthode reçoit un objet Nullable Location qui contient les données de latitude et de longitude.Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. Si la Location valeur n’est pas null , la TrackLocation méthode appelle la OnNext méthode de chaque observateur.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();
   }
}
Public Class LocationTracker : Implements IObservable(Of Location)

   Public Sub New()
      observers = New List(Of IObserver(Of Location))
   End Sub

   Private observers As List(Of IObserver(Of Location))

   Public Function Subscribe(ByVal observer As System.IObserver(Of Location)) As System.IDisposable _
                            Implements System.IObservable(Of Location).Subscribe
      If Not observers.Contains(observer) Then
         observers.Add(observer)
      End If
      Return New Unsubscriber(observers, observer)
   End Function

   Private Class Unsubscriber : Implements IDisposable
      Private _observers As List(Of IObserver(Of Location))
      Private _observer As IObserver(Of Location)

      Public Sub New(ByVal observers As List(Of IObserver(Of Location)), ByVal observer As IObserver(Of Location))
         Me._observers = observers
         Me._observer = observer
      End Sub

      Public Sub Dispose() Implements IDisposable.Dispose
         If _observer IsNot Nothing AndAlso _observers.Contains(_observer) Then
            _observers.Remove(_observer)
         End If
      End Sub
   End Class

   Public Sub TrackLocation(ByVal loc As Nullable(Of Location))
      For Each observer In observers
         If Not loc.HasValue Then
            observer.OnError(New LocationUnknownException())
         Else
            observer.OnNext(loc.Value)
         End If
      Next
   End Sub

   Public Sub EndTransmission()
      For Each observer In observers.ToArray()
         If observers.Contains(observer) Then observer.OnCompleted()
      Next
      observers.Clear()
   End Sub
End Class

Si la Location valeur est null , la TrackLocation méthode instancie un LocationNotFoundException objet, qui est illustré dans l’exemple suivant.If the Location value is null, the TrackLocation method instantiates a LocationNotFoundException object, which is shown in the following example. Elle appelle ensuite la méthode de chaque observateur OnError et la transmet à l' LocationNotFoundException objet.It then calls each observer's OnError method and passes it the LocationNotFoundException object. Notez que LocationNotFoundException dérive de, Exception mais n’ajoute pas de nouveaux membres.Note that LocationNotFoundException derives from Exception but does not add any new members.

public class LocationUnknownException : Exception
{
   internal LocationUnknownException()
   { }
}
Public Class LocationUnknownException : Inherits Exception
   Friend Sub New()
   End Sub
End Class

Les observateurs s’inscrivent pour recevoir des notifications d’un TrackLocation objet en appelant sa IObservable<T>.Subscribe méthode, qui assigne une référence à l’objet observateur à un objet générique privé List<T> .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. La méthode retourne un Unsubscriber objet, qui est une IDisposable implémentation qui permet aux observateurs d’arrêter de recevoir des notifications.The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. La LocationTracker classe comprend également une EndTransmission méthode.The LocationTracker class also includes an EndTransmission method. Quand aucune donnée d’emplacement supplémentaire n’est disponible, la méthode appelle la méthode de chaque observateur, OnCompleted puis efface la liste interne des observateurs.When no further location data is available, the method calls each observer's OnCompleted method and then clears the internal list of observers.

Le code suivant instancie ensuite le fournisseur et l’observateur.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.
Module Module1
   Dim provider As LocationTracker

   Sub Main()
      ' Define a provider and two observers.
      provider = New LocationTracker()
      Dim reporter1 As New LocationReporter("FixedGPS")
      reporter1.Subscribe(provider)
      Dim reporter2 As 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(Nothing)
      provider.EndTransmission()
   End Sub
End Module
' 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.

Remarques

Les IObserver<T> IObservable<T> interfaces et fournissent un mécanisme généralisé pour la notification par envoi de type push, également appelé modèle de conception observateur.The IObserver<T> and IObservable<T> interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. L' IObservable<T> interface représente la classe qui envoie des notifications (le fournisseur) IObserver<T> . l’interface représente la classe qui les reçoit (l’observateur).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 représente la classe qui fournit les informations de notification.T represents the class that provides the notification information.

Une IObserver<T> implémentation s’arrange pour recevoir des notifications d’un fournisseur (une IObservable<T> implémentation) en passant une instance de lui-même à la méthode du fournisseur IObservable<T>.Subscribe .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. Cette méthode retourne un IDisposable objet qui peut être utilisé pour annuler l’abonnement de l’observateur avant que le fournisseur ait terminé d’envoyer des notifications.This method returns an IDisposable object that can be used to unsubscribe the observer before the provider finishes sending notifications.

L' IObserver<T> interface définit les trois méthodes suivantes que l’observateur doit implémenter :The IObserver<T> interface defines the following three methods that the observer must implement:

  • La OnNext méthode, qui est généralement appelée par le fournisseur pour fournir à l’observateur de nouvelles données ou des informations d’État.The OnNext method, which is typically called by the provider to supply the observer with new data or state information.

  • La OnError méthode, qui est généralement appelée par le fournisseur pour indiquer que les données sont indisponibles, inaccessibles ou endommagées, ou que le fournisseur a rencontré une autre condition d’erreur.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.

  • La OnCompleted méthode, qui est généralement appelée par le fournisseur pour indiquer qu’elle a terminé l’envoi des notifications aux observateurs.The OnCompleted method, which is typically called by the provider to indicate that it has finished sending notifications to observers.

Méthodes

OnCompleted()

Signale à l’observateur que le fournisseur a terminé l’envoi des notifications de type push.Notifies the observer that the provider has finished sending push-based notifications.

OnError(Exception)

Notifie l’observateur que le fournisseur a rencontré une condition d’erreur.Notifies the observer that the provider has experienced an error condition.

OnNext(T)

Fournit à l’observateur des nouvelles données.Provides the observer with new data.

S’applique à

Voir aussi