主题<T>.Subscribe 方法

为使用者订阅观察者。

Namespace:System.Reactive.Subjects
装配: System.Reactive.dll) 中的 System.Reactive (

语法

'Declaration
Public Function Subscribe ( _
    observer As IObserver(Of T) _
) As IDisposable
'Usage
Dim instance As Subject
Dim observer As IObserver(Of T)
Dim returnValue As IDisposable

returnValue = instance.Subscribe(observer)
public IDisposable Subscribe(
    IObserver<T> observer
)
public:
virtual IDisposable^ Subscribe(
    IObserver<T>^ observer
) sealed
abstract Subscribe : 
        observer:IObserver<'T> -> IDisposable 
override Subscribe : 
        observer:IObserver<'T> -> IDisposable 
public final function Subscribe(
    observer : IObserver<T>
) : IDisposable

参数

返回值

类型: System.IDisposable
可用于取消对使用者的观察者的订阅的 IDisposable 对象。

实现

IObservable<T>.订阅 (IObserver<T>)

示例

此示例演示了主题类的使用。 字符串类型的 Subject 实例用于订阅两个示例新闻源。 这些源只是以不超过五秒的间隔发布随机新闻头条。 然后,针对使用者的可观测接口创建两个订阅,以接收合并的数据流。 一个订阅将数据流中的每个项报告为“所有新闻”。 另一个订阅筛选流中的每个标题,以仅报告本地标题。 订阅都会将收到的每个标题写入控制台窗口。 当用户按 Enter 键并调用 Dispose 以取消这两个订阅时,处理将终止。

using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reactive.Concurrency;
using System.Threading;

namespace Example
{
  class Program
  {
    static void Main()
    {
      //*****************************************************************************************************//
      //***                                                                                               ***//
      //*** A subject acts similar to a proxy in that it acts as both a subscriber and a publisher        ***//
      //*** It's IObserver interface can be used to subscribe to multiple streams or sequences of data.   ***//
      //*** The data is then published through it's IObservable interface.                                ***//
      //***                                                                                               ***//
      //*** In this example a simple string based subject is used to subscribe to multiple news feeds     ***//
      //*** that provide random news headlines. Subscribers can then subscribe to the subject's           ***//
      //*** observable interface to observe the data stream(s) or a subset ofthe stream(s). Below we      ***//
      //*** subscribe the subject to two different news headline feeds. Then two subscriptions are        ***//
      //*** created: one for delivery of all news headlines, the other receives only local news headlines ***//
      //***                                                                                               ***//
      //*** A local news headline just contains the newsLocation substring ("in your area.").             ***//
      //***                                                                                               ***//
      //*****************************************************************************************************//

      Subject<string> mySubject = new Subject<string>();


      //*********************************************************//
      //*** Create news feed #1 and subscribe mySubject to it ***//
      //*********************************************************//
      NewsHeadlineFeed NewsFeed1 = new NewsHeadlineFeed("Headline News Feed #1");
      NewsFeed1.HeadlineFeed.Subscribe(mySubject);

      //*********************************************************//
      //*** Create news feed #2 and subscribe mySubject to it ***//
      //*********************************************************//
      NewsHeadlineFeed NewsFeed2 = new NewsHeadlineFeed("Headline News Feed #2");
      NewsFeed2.HeadlineFeed.Subscribe(mySubject);


      Console.WriteLine("Subscribing to news headline feeds.\n\nPress ENTER to exit.\n");

      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will receive    ***//
      //*** all headlines.                                                                                ***//
      //*****************************************************************************************************//
      IDisposable allNewsSubscription = mySubject.Subscribe(x => 
      {
        Console.WriteLine("Subscription : All news subscription\n{0}\n", x);
      });


      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will filter for ***//
      //*** only local headlines.                                                                         ***//
      //*****************************************************************************************************//

      IDisposable localNewsSubscription = mySubject.Where(x => x.Contains("in your area.")).Subscribe(x => 
      {
        Console.WriteLine("\n************************************\n" +
                          "***[ Local news headline report ]***\n" +
                          "************************************\n{0}\n\n", x);
      });

      Console.ReadLine();


      //*********************************//
      //*** Cancel both subscriptions ***//
      //*********************************//

      allNewsSubscription.Dispose();
      localNewsSubscription.Dispose();
    }
  }



  //*********************************************************************************//
  //*** The NewsHeadlineFeed class is just a mock news feed in the form of an     ***//
  //*** observable sequence in Reactive Extensions.                               ***//
  //*********************************************************************************//
  class NewsHeadlineFeed
  {
    private string feedName;                     // Feedname used to label the stream
    private IObservable<string> headlineFeed;    // The actual data stream
    private readonly Random rand = new Random(); // Used to stream random headlines.


    //*** A list of predefined news events to combine with a simple ___location string ***//
    static readonly string[] newsEvents = { "A tornado occurred ",
                                            "Weather watch for snow storm issued ",
                                            "A robbery occurred ",
                                            "We have a lottery winner ",
                                            "An earthquake occurred ",
                                            "Severe automobile accident "};

    //*** A list of predefined ___location strings to combine with a news event. ***//
    static readonly string[] newsLocations = { "in your area.",
                                               "in Dallas, Texas.",
                                               "somewhere in Iraq.",
                                               "Lincolnton, North Carolina",
                                               "Redmond, Washington"};

    public IObservable<string> HeadlineFeed
    {
      get { return headlineFeed; }
    }

    public NewsHeadlineFeed(string name)
    {
      feedName = name;

      //*****************************************************************************************//
      //*** Using the Generate operator to generate a continous stream of headline that occur ***//
      //*** randomly within 5 seconds.                                                        ***//
      //*****************************************************************************************//
      headlineFeed = Observable.Generate(RandNewsEvent(),
                                         evt => true,
                                         evt => RandNewsEvent(),
                                         evt => { Thread.Sleep(rand.Next(5000)); return evt; },
                                         Scheduler.ThreadPool);
    }


    //****************************************************************//
    //*** Some very simple formatting of the headline event string ***//
    //****************************************************************//
    private string RandNewsEvent()
    {
      return "Feedname     : " + feedName + "\nHeadline     : " + newsEvents[rand.Next(newsEvents.Length)] + 
             newsLocations[rand.Next(newsLocations.Length)];
    }
  }
}

以下输出是使用示例代码生成的。

Subscribing to news headline feeds.

Press ENTER to exit.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : A robbery occurred somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #1
Headline     : We have a lottery winner in your area.

********************************** [ 当地新闻头条报道 ]********************************** Feedname: 头条新闻源 #1 标题:我们在你的地区有一个彩票中奖者。

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : Severe automobile accident Redmond, Washington

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : We have a lottery winner in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in Dallas, Texas.

Subscription : All news subscription
Feedname     : Headline News Feed #1
Headline     : We have a lottery winner somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : Severe automobile accident somewhere in Iraq.

Subscription : All news subscription
Feedname     : Headline News Feed #2
Headline     : An earthquake occurred in your area.

********************************** [ 当地新闻头条报道 ]********************************** 源名称:头条新闻源 #2 标题:你的地区发生地震。

另请参阅

参考

主题<T> 类

System.Reactive.Subjects 命名空间