IObserver(Of T) Interface

.NET Framework (current version)
 

Provides a mechanism for receiving push-based notifications.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

Public Interface IObserver(Of In T)

Type Parameters

InT

The object that provides notification information.

NameDescription
System_CAPS_pubmethodOnCompleted()

Notifies the observer that the provider has finished sending push-based notifications.

System_CAPS_pubmethodOnError(Exception)

Notifies the observer that the provider has experienced an error condition.

System_CAPS_pubmethodOnNext(T)

Provides the observer with new data.

The IObserver(Of T) and IObservable(Of T) interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The IObservable(Of T) interface represents the class that sends notifications (the provider); the IObserver(Of T) interface represents the class that receives them (the observer). T represents the class that provides the notification information.

An IObserver(Of T) implementation arranges to receive notifications from a provider (an IObservable(Of T) implementation) by passing an instance of itself to the provider's IObservable(Of T).Subscribe method. This method returns an IDisposable object that can be used to unsubscribe the observer before the provider finishes sending notifications.

The IObserver(Of T) interface defines the following three methods that the observer must implement:

  • The OnNext method, which is typically called by the provider to supply the observer with new data or state information.

  • 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.

  • The OnCompleted method, which is typically called by the provider to indicate that it has finished sending notifications to observers.

The following example illustrates the observer design pattern. It defines a Location class that contains latitude and longitude information.

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

The LocationReporter class provides the IObserver(Of T) implementation. It displays information about the current location to the console. Its constructor includes a name parameter, which allows the LocationReporter instance to identify itself in its string output. It also includes a Subscribe method, which wraps a call to the provider's Subscribe method. This enables the method to assign the returned IDisposable reference to a private variable. The LocationReporter class also includes an Unsubscribe method, which calls the IDisposable.Dispose method of the object returned by the IObservable(Of T).Subscribe method. The following code defines the LocationReporter class.

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 LocationTracker class provides the IObservable(Of T) implementation. Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. If the Location value is not null, the TrackLocation method calls the OnNext method of each 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
         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

If the Location value is null, the TrackLocation method instantiates a LocationNotFoundException object, which is shown in the following example. It then calls each observer's OnError method and passes it the LocationNotFoundException object. Note that LocationNotFoundException derives from Exception but does not add any new members.

Public Class LocationUnknownException : Inherits Exception
   Friend Sub New()
   End Sub
End Class

Observers register to receive notifications from a TrackLocation object by calling its IObservable(Of T).Subscribe method, which assigns a reference to the observer object to a private generic List(Of T) object. The method returns an Unsubscriber object, which is an IDisposable implementation that enables observers to stop receiving notifications. The LocationTracker class also includes an EndTransmission method. 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.

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.

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: