IObservable<T> IObservable<T> IObservable<T> IObservable<T> Interface

Definizione

Definisce un provider per la notifica basata su push.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)

Parametri di tipo

T

Oggetto che fornisce informazioni di notifica.The object that provides notification information.

Derivato

Esempi

L'esempio seguente illustra lo schema progettuale osservatore.The following example illustrates the observer design pattern. Definisce un Location classe che contiene le informazioni di latitudine e longitudine.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

Il LocationTracker classe fornisce il IObservable<T> implementazione.The LocationTracker class provides the IObservable<T> implementation. Relativi TrackLocation metodo viene passato un valore nullable Location oggetto che contiene i dati di latitudine e longitudine.Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. Se il Location valore non null, il TrackLocation chiamate al metodo il OnNext metodo per ogni osservatore.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

Se il Location valore è null, il TrackLocation crea un'istanza di metodo un LocationUnknownException oggetto, che viene visualizzato nell'esempio seguente.If the Location value is null, the TrackLocation method instantiates a LocationUnknownException object, which is shown in the following example. Chiama quindi ogni osservatore OnError metodo e passa il LocationUnknownException oggetto.It then calls each observer's OnError method and passes it the LocationUnknownException object. Si noti che LocationUnknownException deriva da Exception, ma non aggiunge tutti i nuovi membri.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

Registrare gli Observer per ricevere notifiche da un TrackLocation chiamando relativi IObservable<T>.Subscribe metodo, che assegna un riferimento all'oggetto osservatore per un privato generico List<T> oggetto.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. Il metodo restituisce un Unsubscriber oggetto, ovvero un IDisposable implementazione che consente agli osservatori di smettere di ricevere notifiche.The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. Il LocationTracker classe include anche un EndTransmission (metodo).The LocationTracker class also includes an EndTransmission method. Quando non esistono altri dati di posizione sono disponibili, il metodo chiama ogni osservatore OnCompleted (metodo) e quindi Cancella l'elenco interno degli osservatori.When no further location data is available, the method calls each observer's OnCompleted method and then clears the internal list of observers.

In questo esempio, il LocationReporter classe fornisce il IObserver<T> implementazione.In this example, the LocationReporter class provides the IObserver<T> implementation. Visualizza informazioni sulla posizione corrente nella console.It displays information about the current location to the console. Il costruttore include un name parametro, che consente la LocationReporter istanza per identificare se stessa nella stringa restituita.Its constructor includes a name parameter, which enables the LocationReporter instance to identify itself in its string output. Include anche un Subscribe metodo, che esegue il wrapping di una chiamata al provider Subscribe (metodo).It also includes a Subscribe method, which wraps a call to the provider's Subscribe method. In questo modo il metodo a cui assegnare l'oggetto restituito IDisposable riferimento a una variabile privata.This allows the method to assign the returned IDisposable reference to a private variable. Il LocationReporter classe include anche un' Unsubscribe metodo, che chiama il IDisposable.Dispose dell'oggetto restituito dal metodo il IObservable<T>.Subscribe (metodo).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. Il codice seguente definisce il 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

Il codice seguente crea poi il provider e l'osservatore.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.

Commenti

Il IObserver<T> e IObservable<T> interfacce forniscono un meccanismo per la notifica basata su push, noto anche come modello di progettazione osservatore generalizzato.The IObserver<T> and IObservable<T> interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. Il IObservable<T> interfaccia rappresenta la classe che invia le notifiche (provider); il IObserver<T> interfaccia rappresenta la classe che li (l'osservatore) riceve.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 rappresenta la classe che fornisce le informazioni di notifica.T represents the class that provides the notification information. In alcune notifiche basate su push, il IObserver<T> implementazione e T può rappresentare lo stesso tipo.In some push-based notifications, the IObserver<T> implementation and T can represent the same type.

Il provider deve implementare un singolo metodo, Subscribe, che indica che un osservatore desidera ricevere le notifiche basate su push.The provider must implement a single method, Subscribe, that indicates that an observer wants to receive push-based notifications. I chiamanti del metodo passano un'istanza di observer.Callers to the method pass an instance of the observer. Il metodo restituisce un IDisposable implementazione che consente agli osservatori di annullare le notifiche in qualsiasi momento prima che il provider è stato arrestato vengono inviati.The method returns an IDisposable implementation that enables observers to cancel notifications at any time before the provider has stopped sending them.

In qualsiasi momento, un determinato provider potrebbe essere zero, uno o più Observer.At any given time, a given provider may have zero, one, or multiple observers. Il provider è responsabile per l'archiviazione di riferimenti agli Observer e assicurandosi che siano validi prima di inviare le notifiche.The provider is responsible for storing references to observers and ensuring that they are valid before it sends notifications. Il IObservable<T> interfaccia non fare supposizioni sul numero di osservatori o l'ordine in cui vengono inviate le notifiche.The IObservable<T> interface does not make any assumptions about the number of observers or the order in which notifications are sent.

Il provider invia i seguenti tre tipi di notifiche all'observer chiamando IObserver<T> metodi:The provider sends the following three kinds of notifications to the observer by calling IObserver<T> methods:

  • I dati correnti.The current data. Il provider può richiamare il IObserver<T>.OnNext metodo per passare l'osservatore una T oggetto contenente dati correnti, i dati modificati o nuovi dati.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 condizione di errore.An error condition. Il provider può richiamare il IObserver<T>.OnError metodo per inviare una notifica all'osservatore che si è verificata una condizione di errore.The provider can call the IObserver<T>.OnError method to notify the observer that some error condition has occurred.

  • Non esistono altri dati.No further data. Il provider può richiamare il IObserver<T>.OnCompleted metodo per inviare una notifica all'osservatore che ha terminato l'invio di notifiche.The provider can call the IObserver<T>.OnCompleted method to notify the observer that it has finished sending notifications.

Metodi

Subscribe(IObserver<T>) Subscribe(IObserver<T>) Subscribe(IObserver<T>) Subscribe(IObserver<T>)

Notifica al provider che un osservatore deve ricevere notifiche.Notifies the provider that an observer is to receive notifications.

Si applica a

Vedi anche