IObservable<T> Interfejs

Definicja

Definiuje dostawcę powiadomień wypychanych.

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

Parametry typu

T

Obiekt, który dostarcza informacje o powiadomieniach.

Ten parametr typu jest kowariantny. Oznacza to, że możesz użyć typu, który został przez Ciebie określony, lub dowolnego typu, który jest bardziej pochodny. Aby uzyskać więcej informacji o kowariancji i kontrawariancji, zobacz Kowariancja i kontrawariancja w typach ogólnych.
Pochodne

Przykłady

Poniższy przykład ilustruje wzorzec projektowy obserwatora. Definiuje klasę zawierającą Location informacje o szerokości i długości geograficznej.

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; } }
}
[<Struct>]
type Location =
    { Latitude: double
      Longitude: double }
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

Klasa LocationTracker zapewnia implementację IObservable<T> . Jej TrackLocation metoda jest przekazywana obiekt dopuszczający Location wartość null, który zawiera dane szerokości geograficznej i długości geograficznej. Location Jeśli wartość nie nulljest , TrackLocation metoda wywołuje metodę OnNext każdego obserwatora.

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();
   }
}
type Unsubscriber(observers: ResizeArray<IObserver<Location>>, observer: IObserver<Location>) =
    interface IDisposable with
        member _.Dispose() =
            if observer <> null && observers.Contains observer then
                observers.Remove observer |> ignore

type LocationTracker() =
    let observers = ResizeArray<IObserver<Location>>()

    interface IObservable<Location> with
        member _.Subscribe(observer) =
            if observers.Contains observer |> not then
                observers.Add observer
            new Unsubscriber(observers, observer)

    member _.TrackLocation(loc: Nullable<Location>) =
        for observer in observers do
            if not loc.HasValue then
                observer.OnError LocationUnknownException
            else
                observer.OnNext loc.Value

    member _.EndTransmission() =
        for observer in observers.ToArray() do
            if observers.Contains observer then
                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

Location Jeśli wartość to null, TrackLocation metoda tworzy wystąpienie LocationUnknownException obiektu, który jest pokazany w poniższym przykładzie. Następnie wywołuje metodę każdego obserwatora OnError i przekazuje go do LocationUnknownException obiektu. Należy pamiętać, że LocationUnknownException pochodzi z Exceptionklasy , ale nie dodaje żadnych nowych elementów członkowskich.

public class LocationUnknownException : Exception
{
   internal LocationUnknownException()
   { }
}
exception LocationUnknownException
Public Class LocationUnknownException : Inherits Exception
   Friend Sub New()
   End Sub
End Class

Obserwatorzy rejestrują się w celu odbierania powiadomień z TrackLocation obiektu przez wywołanie jego IObservable<T>.Subscribe metody, która przypisuje odwołanie do obiektu obserwatora do prywatnego obiektu ogólnego List<T> . Metoda zwraca Unsubscriber obiekt, który jest implementacją IDisposable , która umożliwia obserwatorom zaprzestanie odbierania powiadomień. Klasa LocationTracker zawiera również metodę EndTransmission . Jeśli nie są dostępne żadne dalsze dane lokalizacji, metoda wywołuje metodę każdego obserwatora OnCompleted , a następnie czyści wewnętrzną listę obserwatorów.

W tym przykładzie LocationReporter klasa udostępnia implementację IObserver<T> . Wyświetla informacje o bieżącej lokalizacji w konsoli programu . Jego konstruktor zawiera name parametr, który umożliwia wystąpieniu LocationReporter zidentyfikowanie się w danych wyjściowych ciągu. Zawiera również metodę Subscribe , która opakowuje wywołanie metody dostawcy Subscribe . Dzięki temu metoda może przypisać zwrócone IDisposable odwołanie do zmiennej prywatnej. Klasa LocationReporter zawiera również metodę , która wywołuje IDisposable.Dispose metodę Unsubscribe obiektu zwróconego przez metodę IObservable<T>.Subscribe . Poniższy kod definiuje klasę LocationReporter .

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();
   }
}
open System

type LocationReporter(name) =
    let mutable unsubscriber = Unchecked.defaultof<IDisposable>

    member _.Name = name

    member this.Subscribe(provider: IObservable<Location>) =
        if provider <> null then
            unsubscriber <- provider.Subscribe this

    member _.Unsubscribe() =
        unsubscriber.Dispose()

    interface IObserver<Location> with
        member this.OnCompleted() =
            printfn $"The Location Tracker has completed transmitting data to {name}."
            this.Unsubscribe()

        member _.OnError(_) =
            printfn $"{name}: The location cannot be determined."

        member _.OnNext(value) =
            printfn $"{name}: The current location is {value.Latitude}, {value.Longitude}"
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

Następnie poniższy kod tworzy wystąpienie dostawcy i obserwatora.

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.
open System

// Define a provider and two observers.
let provider = LocationTracker()
let reporter1 = LocationReporter "FixedGPS"
reporter1.Subscribe provider
let reporter2 = LocationReporter "MobileGPS"
reporter2.Subscribe provider

provider.TrackLocation { Latitude = 47.6456; Longitude = -122.1312 }
reporter1.Unsubscribe()
provider.TrackLocation { Latitude = 47.6677; Longitude = -122.1199 }
provider.TrackLocation(Nullable())
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.

Uwagi

Interfejsy IObserver<T> i IObservable<T> zapewniają uogólniony mechanizm powiadomień wypychanych, znany również jako wzorzec projektowy obserwatora. Interfejs IObservable<T> reprezentuje klasę, która wysyła powiadomienia (dostawca); IObserver<T> interfejs reprezentuje klasę, która je odbiera (obserwatora). T reprezentuje klasę, która dostarcza informacje o powiadomieniach. W przypadku niektórych powiadomień wypychanych implementacja IObserver<T> i T może reprezentować ten sam typ.

Dostawca musi zaimplementować jedną metodę , Subscribektóra wskazuje, że obserwator chce otrzymywać powiadomienia wypychane. Wywołania metody przekazują wystąpienie obserwatora. Metoda zwraca implementację IDisposable , która umożliwia obserwatorom anulowanie powiadomień w dowolnym momencie, zanim dostawca przestał je wysyłać.

W dowolnym momencie dany dostawca może mieć zero, jeden lub wielu obserwatorów. Dostawca jest odpowiedzialny za przechowywanie odwołań do obserwatorów i upewnienie się, że są one prawidłowe przed wysłaniem powiadomień. Interfejs IObservable<T> nie przyjmuje żadnych założeń dotyczących liczby obserwatorów ani kolejności wysyłania powiadomień.

Dostawca wysyła następujące trzy rodzaje powiadomień do obserwatora przez wywołanie IObserver<T> metod:

  • Bieżące dane. Dostawca może wywołać metodę IObserver<T>.OnNext , aby przekazać obserwatorowi T obiekt zawierający bieżące dane, zmienione dane lub świeże dane.

  • Warunek błędu. Dostawca może wywołać metodę IObserver<T>.OnError , aby powiadomić obserwatora o wystąpieniu pewnego warunku błędu.

  • Brak dalszych danych. Dostawca może wywołać metodę , aby powiadomić obserwatora o zakończeniu IObserver<T>.OnCompleted wysyłania powiadomień.

Metody

Subscribe(IObserver<T>)

Powiadamia dostawcę, że obserwator ma otrzymywać powiadomienia.

Dotyczy

Zobacz też