Прочетете на английски Редактиране

Споделяне чрез


IObservable<T>.Subscribe(IObserver<T>) Method

Definition

Notifies the provider that an observer is to receive notifications.

C#
public IDisposable Subscribe(IObserver<out T> observer);

Parameters

observer
IObserver<T>

The object that is to receive notifications.

Returns

A reference to an interface that allows observers to stop receiving notifications before the provider has finished sending them.

Examples

The following example illustrates the Subscribe method for an application that reports latitude and longitude information. It defines an IList<T> collection object that stores references to all observers. It also returns a private class named Unsubscriber that implements the IDisposable interface and enables subscribers to stop receiving event notifications. See the Example section of the IObservable<T> topic for the complete example.

C#
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);
   }
}

Remarks

The Subscribe method must be called to register an observer for push-based notifications. A typical implementation of the Subscribe method does the following:

  • It stores a reference to the observer in a collection object, such as a List<T> object.

  • It returns a reference to an IDisposable interface. This enables observers to unsubscribe (that is, to stop receiving notifications) before the provider has finished sending them and called the subscriber's OnCompleted method.

At any given time, a particular instance of an IObservable<T> implementation is responsible for handling all subscriptions and notifying all subscribers. Unless the documentation for a particular IObservable<T> implementation indicates otherwise, observers should make no assumptions about the IObservable<T> implementation, such as the order of notifications that multiple observers will receive.

Applies to

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

See also