IObservable<T> 接口

定义

定义基于推送的通知的提供程序。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)

类型参数

T

提供通知信息的对象。The object that provides notification information.

派生

示例

下面的示例演示观察者设计模式。The following example illustrates the observer design pattern. 它定义Location包含纬度和经度信息的类。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

LocationTrackerIObservable<T>提供实现。The LocationTracker class provides the IObservable<T> implementation. TrackLocation其方法传递包含纬度Location和经度数据的可以为 null 的对象。Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. 如果值不null TrackLocationOnNext , 则方法调用每个观察程序的方法。 LocationIf 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

如果值为null,则该TrackLocation方法将实例化对象,如下例所示。LocationUnknownException LocationIf the Location value is null, the TrackLocation method instantiates a LocationUnknownException object, which is shown in the following example. 然后, 它调用每个OnError观察程序的方法并LocationUnknownException向其传递对象。It then calls each observer's OnError method and passes it the LocationUnknownException object. 请注意, Exception派生自, 但不添加任何新成员。 LocationUnknownExceptionNote 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

观察者通过调用其TrackLocation IObservable<T>.Subscribe方法来注册以接收来自对象的通知, 该方法将对观察者对象的引用分配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. 方法返回一个Unsubscriber对象, 该对象是一个IDisposable实现, 它使观察程序可以停止接收通知。The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. LocationTracker类还EndTransmission包含方法。The LocationTracker class also includes an EndTransmission method. 当没有更多的位置数据可用时, 方法会调用每OnCompleted个观察程序的方法, 然后清除观察程序的内部列表。When no further location data is available, the method calls each observer's OnCompleted method and then clears the internal list of observers.

在此示例中, LocationReporterIObserver<T>提供了实现。In this example, the LocationReporter class provides the IObserver<T> implementation. 它显示有关当前控制台位置的信息。It displays information about the current location to the console. 其构造函数包含name一个参数, 该参数LocationReporter可使实例在其字符串输出中标识自身。Its constructor includes a name parameter, which enables the LocationReporter instance to identify itself in its string output. 它还包括一个Subscribe方法, 该方法将调用提供程序的Subscribe方法。It also includes a Subscribe method, which wraps a call to the provider's Subscribe method. 这允许方法为私有变量分配返回IDisposable的引用。This allows the method to assign the returned IDisposable reference to a private variable. 类还包括一个Unsubscribe IObservable<T>.Subscribe方法, 该方法调用方法返回的对象的方法。IDisposable.Dispose LocationReporterThe 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. 下面的代码定义LocationReporter类。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

然后, 以下代码实例化提供程序和观察程序。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.

注解

IObserver<T>IObservable<T>接口为基于推送的通知 (也称为观察者设计模式) 提供通用机制。The IObserver<T> and IObservable<T> interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. 接口表示发送通知的类 (提供程序) IObserver<T> ; 接口表示接收它们的类 (观察者)。 IObservable<T>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表示提供通知信息的类。T represents the class that provides the notification information. 在某些基于推送的通知中, IObserver<T>实现和T可以表示相同类型。In some push-based notifications, the IObserver<T> implementation and T can represent the same type.

提供程序必须实现一个方法, Subscribe该方法指示观察者要接收基于推送的通知。The provider must implement a single method, Subscribe, that indicates that an observer wants to receive push-based notifications. 方法的调用方传递观察程序的实例。Callers to the method pass an instance of the observer. 方法返回一个IDisposable实现, 该实现使观察程序可以在提供程序停止发送通知之前随时取消通知。The method returns an 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. IObservable<T>接口不对观察器数或发送通知的顺序作出任何假设。The IObservable<T> interface does not make any assumptions about the number of observers or the order in which notifications are sent.

提供程序通过调用IObserver<T>方法向观察者发送以下三种类型的通知:The provider sends the following three kinds of notifications to the observer by calling IObserver<T> methods:

  • 当前数据。The current data. 提供程序可以调用IObserver<T>.OnNext方法来传递T包含当前数据、更改的数据或新数据的对象。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.

  • 错误情况。An error condition. 提供程序可以调用IObserver<T>.OnError方法, 通知观察者发生了某种错误情况。The provider can call the IObserver<T>.OnError method to notify the observer that some error condition has occurred.

  • 无更多数据。No further data. 提供程序可以调用IObserver<T>.OnCompleted方法, 通知观察者它已完成发送通知。The provider can call the IObserver<T>.OnCompleted method to notify the observer that it has finished sending notifications.

方法

Subscribe(IObserver<T>)

通知提供程序:某观察程序将要接收通知。Notifies the provider that an observer is to receive notifications.

适用于

另请参阅