IObserver<T> IObserver<T> IObserver<T> IObserver<T> Interface


提供用于接收基于推送的通知的机制。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)



提供通知信息的对象。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)
   { = latitude;
      this.lon = longitude;

   public double Latitude
   { get { return; } }

   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) = latitude
      Me.lon = longitude
   End Sub

   Public ReadOnly Property Latitude As Double
      End Get
   End Property

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

LocationReporter类提供了IObserver<T>实现。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 allows 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 enables the method to assign the returned IDisposable reference to a private variable. LocationReporter类还包括Unsubscribe方法,调用IDisposable.Dispose方法返回的对象IObservable<T>.Subscribe方法。The LocationReporter class also includes an Unsubscribe method, which calls the IDisposable.Dispose method of the object 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);

   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()
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
         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)
   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()
   End Sub
End Class

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

   public void TrackLocation(Nullable<Location> loc)
      foreach (var observer in observers) {
         if (! loc.HasValue)
            observer.OnError(new LocationUnknownException());

   public void EndTransmission()
      foreach (var observer in observers.ToArray())
         if (observers.Contains(observer))

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
      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
         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())
         End If
   End Sub

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

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

观察程序注册以接收来自通知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.

提供程序和观察者,然后实例化下面的代码。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");
      LocationReporter reporter2 = new LocationReporter("MobileGPS");

      provider.TrackLocation(new Location(47.6456, -122.1312));
      provider.TrackLocation(new Location(47.6677, -122.1199));
// 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")
      Dim reporter2 As New LocationReporter("MobileGPS")

      provider.TrackLocation(New Location(47.6456, -122.1312))
      provider.TrackLocation(New Location(47.6677, -122.1199))
   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. IObservable<T>接口表示发送通知 (该提供程序;) 的类IObserver<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>实现来排列以从提供程序接收通知 (IObservable<T>实现) 通过将自身的实例传递到提供程序的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. 此方法返回IDisposable对象,它可用于取消订阅观察者提供程序之前完成发送通知。This method returns an IDisposable object that can be used to unsubscribe the observer before the provider finishes sending notifications.

IObserver<T>接口定义观察程序必须实现以下三种方法:The IObserver<T> interface defines the following three methods that the observer must implement:

  • OnNext通常由提供程序提供的新数据或状态信息的观察程序调用的方法。The OnNext method, which is typically called by the provider to supply the observer with new data or state information.

  • OnError方法,通常会调用由提供程序指示数据不可用,不可访问,或已损坏,或提供程序遇到其他错误条件。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.

  • OnCompleted通常由提供程序,以指示它已完成将通知发送给观察程序调用的方法。The OnCompleted method, which is typically called by the provider to indicate that it has finished sending notifications to observers.


OnCompleted() OnCompleted() OnCompleted() OnCompleted()

通知观察者提供程序已完成发送基于推送的通知。Notifies the observer that the provider has finished sending push-based notifications.

OnError(Exception) OnError(Exception) OnError(Exception) OnError(Exception)

通知观察者,提供程序遇到错误情况。Notifies the observer that the provider has experienced an error condition.

OnNext(T) OnNext(T) OnNext(T) OnNext(T)

向观察者提供新数据。Provides the observer with new data.