IObservable<T> Interfaz

Definición

Define un proveedor para la notificación mediante inserción.Defines a provider for push-based notification.

generic <typename T>
public interface class IObservable
public interface IObservable<out T>
type IObservable<'T> = interface
Public Interface IObservable(Of Out T)

Parámetros de tipo

T

Objeto que proporciona información sobre la notificación.The object that provides notification information.

Derivado

Ejemplos

En el ejemplo siguiente se muestra el modelo de diseño de observador.The following example illustrates the observer design pattern. Define una Location clase que contiene información de latitud y longitud.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 LocationTracker clase proporciona la IObservable<T> implementación de.The LocationTracker class provides the IObservable<T> implementation. A TrackLocation su método se le pasa un Location objeto que acepta valores NULL y que contiene los datos de latitud y longitud.Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. Si el Location valor no nulles, el TrackLocation método llama al OnNext método de cada observador.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 el Location valor es null, el TrackLocation método crea una instancia LocationUnknownException de un objeto, que se muestra en el ejemplo siguiente.If the Location value is null, the TrackLocation method instantiates a LocationUnknownException object, which is shown in the following example. A continuación, llama al método OnError de cada observador y le LocationUnknownException pasa el objeto.It then calls each observer's OnError method and passes it the LocationUnknownException object. Tenga en LocationUnknownException cuenta que se Exceptionderiva de, pero no agrega ningún miembro nuevo.Note that LocationUnknownException 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

Los observadores se registran para recibir notificaciones TrackLocation de un objeto llamando IObservable<T>.Subscribe a su método, que asigna una referencia al objeto de observador a un objeto genérico List<T> privado.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. El método devuelve un Unsubscriber objeto, que es una IDisposable implementación que permite a los observadores dejar de recibir notificaciones.The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. La LocationTracker clase también incluye un EndTransmission método.The LocationTracker class also includes an EndTransmission method. Cuando no hay más datos de ubicación disponibles, el método llama al método OnCompleted de cada observador y, a continuación, borra la lista interna de observadores.When no further location data is available, the method calls each observer's OnCompleted method and then clears the internal list of observers.

En este ejemplo, la LocationReporter clase proporciona la IObserver<T> implementación de.In this example, the LocationReporter class provides the IObserver<T> implementation. Muestra información sobre la ubicación actual en la consola.It displays information about the current location to the console. Su constructor incluye un name parámetro, que permite a LocationReporter la instancia identificarse en la salida de la cadena.Its constructor includes a name parameter, which enables the LocationReporter instance to identify itself in its string output. También incluye un Subscribe método, que encapsula una llamada al método del Subscribe proveedor.It also includes a Subscribe method, which wraps a call to the provider's Subscribe method. Esto permite al método asignar la referencia devuelta IDisposable a una variable privada.This allows the method to assign the returned IDisposable reference to a private variable. La LocationReporter clase también incluye un Unsubscribe método, que llama al IDisposable.Dispose método del objeto devuelto por el IObservable<T>.Subscribe método.The LocationReporter class also includes an Unsubscribe method, which calls the IDisposable.Dispose method of the object that is returned by the IObservable<T>.Subscribe method. En el código siguiente se LocationReporter define la clase.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

El código siguiente crea una instancia del proveedor y el observador.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.

Comentarios

Las IObserver<T> interfaces IObservable<T> y proporcionan un mecanismo generalizado para la notificación basada en la instalación, también conocido como modelo de diseño de observador.The IObserver<T> and IObservable<T> interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. La IObservable<T> interfaz representa la clase que envía notificaciones (el proveedor); la IObserver<T> interfaz representa la clase que las recibe (el observador).The IObservable<T> interface represents the class that sends notifications (the provider); the IObserver<T> interface represents the class that receives them (the observer). Trepresenta la clase que proporciona la información de notificación.T represents the class that provides the notification information. En algunas notificaciones basadas en la instalación, IObserver<T> la implementación T de y puede representar el mismo tipo.In some push-based notifications, the IObserver<T> implementation and T can represent the same type.

El proveedor debe implementar un método único, Subscribe, que indica que un observador desea recibir notificaciones basadas en la instalación.The provider must implement a single method, Subscribe, that indicates that an observer wants to receive push-based notifications. Los llamadores al método pasan una instancia del observador.Callers to the method pass an instance of the observer. El método devuelve una IDisposable implementación que permite a los observadores cancelar las notificaciones en cualquier momento antes de que el proveedor haya dejado de enviarlas.The method returns an IDisposable implementation that enables observers to cancel notifications at any time before the provider has stopped sending them.

En un momento dado, un proveedor determinado puede tener cero, uno o varios observadores.At any given time, a given provider may have zero, one, or multiple observers. El proveedor es responsable de almacenar las referencias a los observadores y de asegurarse de que son válidas antes de enviar notificaciones.The provider is responsible for storing references to observers and ensuring that they are valid before it sends notifications. La IObservable<T> interfaz no realiza ninguna suposición sobre el número de observadores o el orden en el que se envían las notificaciones.The IObservable<T> interface does not make any assumptions about the number of observers or the order in which notifications are sent.

El proveedor envía los tres tipos de notificaciones siguientes al observador llamando IObserver<T> a los métodos:The provider sends the following three kinds of notifications to the observer by calling IObserver<T> methods:

  • Los datos actuales.The current data. El proveedor puede llamar IObserver<T>.OnNext al método para pasar al observador un T objeto que tenga datos actualizados, datos modificados o datos nuevos.The provider can call the IObserver<T>.OnNext method to pass the observer a T object that has current data, changed data, or fresh data.

  • Una condición de error.An error condition. El proveedor puede llamar IObserver<T>.OnError al método para notificar al observador que se ha producido alguna condición de error.The provider can call the IObserver<T>.OnError method to notify the observer that some error condition has occurred.

  • No hay más datos.No further data. El proveedor puede llamar IObserver<T>.OnCompleted al método para notificar al observador que ha terminado de enviar notificaciones.The provider can call the IObserver<T>.OnCompleted method to notify the observer that it has finished sending notifications.

Métodos

Subscribe(IObserver<T>)

Notifica al proveedor que un observador va a recibir las notificaciones.Notifies the provider that an observer is to receive notifications.

Se aplica a

Consulte también: