IObserver<T> 인터페이스

정의

푸시 기반 알림을 받기 위한 메커니즘을 제공합니다.

generic <typename T>
public interface class IObserver
public interface IObserver<in T>
type IObserver<'T> = interface
Public Interface IObserver(Of In T)

형식 매개 변수

T

알림 정보를 제공하는 개체입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.
파생

예제

다음 예제에서는 관찰자 디자인 패턴을 보여 줍니다. 위도 및 경도 정보를 포함하는 클래스를 정의 Location 합니다.

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

클래스는 LocationReporter 구현을 IObserver<T> 제공합니다. 콘솔의 현재 위치에 대한 정보를 표시합니다. 해당 생성자에는 인스턴스가 name 문자열 출력에서 자신을 식별할 수 있는 LocationReporter 매개 변수가 포함됩니다. 또한 공급자의 Subscribe 메서드에 Subscribe 대한 호출을 래핑하는 메서드도 포함됩니다. 이렇게 하면 메서드가 반환 IDisposable 된 참조를 프라이빗 변수에 할당할 수 있습니다. 클래스에는 LocationReporter 메서드에서 Unsubscribe 반환 IObservable<T>.Subscribe 된 개체의 메서드를 호출 IDisposable.Dispose 하는 메서드도 포함됩니다. 다음 코드는 클래스를 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

클래스는 LocationTracker 구현을 IObservable<T> 제공합니다. 해당 TrackLocation 메서드는 위도 및 경도 데이터를 포함하는 nullable Location 개체에 전달됩니다. 값이 Location 아닌 null경우 메서드는 TrackLocation 각 관찰자의 메서드를 OnNext 호출합니다.

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 면 메서드는 null``TrackLocation 다음 예제에 표시된 개체를 인스턴스화 LocationNotFoundException 합니다. 그런 다음 각 관찰자의 OnError 메서드를 호출하고 개체를 LocationNotFoundException 전달합니다. LocationNotFoundException 파생 Exception 되지만 새 멤버는 추가하지 않습니다.

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

관찰자는 해당 메서드를 호출 IObservable<T>.Subscribe 하여 개체로부터 TrackLocation 알림을 수신하도록 등록합니다. 이 메서드는 관찰자 개체에 대한 참조를 프라이빗 제네릭 List<T> 개체에 할당합니다. 이 메서드는 관찰자가 Unsubscriber 알림 수신을 IDisposable 중지할 수 있도록 하는 구현인 개체를 반환합니다. 클래스에는 LocationTracker 메서드도 포함됩니다 EndTransmission . 더 이상 위치 데이터를 사용할 수 없는 경우 메서드는 각 관찰자의 OnCompleted 메서드를 호출한 다음 내부 관찰자 목록을 지웁니다.

그런 다음, 다음 코드는 공급자와 관찰자를 인스턴스화합니다.

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.

설명

IObservable<T> 인터페이스는 IObserver<T> 관찰자 디자인 패턴이라고도 하는 푸시 기반 알림을 위한 일반화된 메커니즘을 제공합니다. 인터페이스는 IObservable<T> 알림을 보내는 클래스(공급자 IObserver<T> )를 나타내며, 인터페이스는 알림을 받는 클래스(관찰자)를 나타냅니다. T 는 알림 정보를 제공하는 클래스를 나타냅니다.

구현은 IObserver<T> 공급자의 메서드에 자체 인스턴스를 전달하여 공급자( IObservable<T> 구현)로부터 알림을 받도록 IObservable<T>.Subscribe 정렬합니다. 이 메서드는 IDisposable 공급자가 알림 보내기를 완료하기 전에 관찰자 구독을 취소하는 데 사용할 수 있는 개체를 반환합니다.

인터페이스는 IObserver<T> 관찰자가 구현해야 하는 다음 세 가지 메서드를 정의합니다.

  • OnNext 일반적으로 새 데이터 또는 상태 정보를 관찰자에게 제공하기 위해 공급자가 호출하는 메서드입니다.

  • OnError 일반적으로 공급자가 데이터를 사용할 수 없거나, 액세스할 수 없거나, 손상되었거나, 공급자가 다른 오류 조건을 경험했음을 나타내는 메서드입니다.

  • OnCompleted 일반적으로 공급자가 관찰자에게 알림 보내기를 완료했음을 나타내기 위해 호출되는 메서드입니다.

메서드

OnCompleted()

공급자가 푸시 기반 알림 전송을 완료했음을 관찰자에게 알립니다.

OnError(Exception)

공급자에 오류 조건이 있음을 옵서버에 알립니다.

OnNext(T)

관찰자에게 새 데이터를 제공합니다.

적용 대상

추가 정보