IObservable<T> IObservable<T> IObservable<T> IObservable<T> Interface

정의

푸시 기반 알림을 위한 공급자를 정의합니다.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

합니다 LocationTracker 클래스를 제공 합니다 IObservable<T> 구현 합니다.The LocationTracker class provides the IObservable<T> implementation. 해당 TrackLocation 메서드는 null을 허용 되는지를 Location 위도 및 경도 데이터가 들어 있는 개체입니다.Its TrackLocation method is passed a nullable Location object that contains the latitude and longitude data. 경우는 Location 값이 아닙니다 nullTrackLocation 메서드 호출을 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)) 
         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

경우는 Location 값이 null, TrackLocation 메서드를 만드는 데는 LocationUnknownException 다음 예제에 나와 있는 개체입니다.If 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. 사실은 LocationUnknownException 에서 파생 Exception, 하지만 새 멤버를 추가 하지 않습니다.Note 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 private 제네릭 observer 개체에 대 한 참조를 할당 하는 메서드를 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.

이 예제에서는 합니다 LocationReporter 클래스를 제공 합니다 IObserver<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 private 변수를 참조 합니다.This allows 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 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. 합니다 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> 구현 및 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.

지정된 된 시간에 지정된 된 공급자에는 0 개 또는 하나 이상의 관찰자가 있을 수 있습니다.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>) Subscribe(IObserver<T>) Subscribe(IObserver<T>) Subscribe(IObserver<T>)

옵서버가 알림을 받을 것임을 공급자에 알립니다.Notifies the provider that an observer is to receive notifications.

적용 대상

추가 정보