共用方式為


ReplaySubject < T > 建構函式

建立可重新執行的主旨。

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

語法

'Declaration
Public Sub New
'Usage

Dim instance As New ReplaySubject()
public ReplaySubject()
public:
ReplaySubject()
new : unit -> ReplaySubject
public function ReplaySubject()

範例

在此範例中,我們已建立 NewsHeadlineFeed 類別,其只是以可觀察字串序列的形式模擬新聞摘要。 它會使用 Generate 運算子,在三秒內持續產生隨機新聞標題。

系統會建立 ReplaySubject 來訂閱 NewsHeadlineFeed 類別的兩個新聞摘要。 在主旨訂閱摘要之前,時間戳記運算子會使用時間戳每個標題。 因此 ReplaySubject 實際上訂閱的順序是 IObservable < Timestamped < 字串 >> 類型。 當標題序列時間戳記之後,訂閱者可以訂閱主體的可觀察介面,以根據時間戳記來觀察資料流程 ( () 或資料流程子集) (的資料流程子集。

ReplaySubject 會緩衝接收的專案。 因此,稍後建立的訂用帳戶可以存取已緩衝和發行序列中的專案。 系統會建立 ReplaySubject 的訂用帳戶,只接收在建立本機新聞訂閱前 10 秒發生的本機新聞頭條。 因此,我們基本上會有 ReplaySubject 「replay」 先前發生 10 秒的情況。

本機新聞標題只包含新聞位置子字串 (「在您的區域中」。) 。

using System;
using System.Reactive;
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 ReplaySubject is used to subscribe to multiple news feeds            ***//
      //*** that provide random news headlines. Before the subject is subscribed to the feeds, we use     ***//
      //*** Timestamp operator to timestamp each headline. Subscribers can then subscribe to the subject  ***//
      //*** observable interface to observe the data stream(s) or a subset of the stream(s) based on      ***//
      //*** time.                                                                                         ***//
      //***                                                                                               ***//
      //*** A ReplaySubject buffers items it receives. So a subscription created at a later time can      ***//
      //*** access items from the sequence which have already been published.                             ***//
      //***                                                                                               ***//
      //*** A subscriptions is created to the ReplaySubject that receives only local news headlines which ***//
      //*** occurred 10 seconds before the local news subscription was created. So we basically have the  ***//
      //*** ReplaySubject "replay" what happened 10 seconds earlier.                                      ***//
      //***                                                                                               ***//
      //*** A local news headline just contains the newsLocation substring ("in your area.").             ***//
      //***                                                                                               ***//
      //*****************************************************************************************************//

      ReplaySubject<Timestamped<string>> myReplaySubject = new ReplaySubject<Timestamped<String>>();


      //*****************************************************************//
      //*** Create news feed #1 and subscribe the ReplaySubject to it ***//
      //*****************************************************************//

      NewsHeadlineFeed NewsFeed1 = new NewsHeadlineFeed("Headline News Feed #1");
      NewsFeed1.HeadlineFeed.Timestamp().Subscribe(myReplaySubject);


      //*****************************************************************//
      //*** Create news feed #2 and subscribe the ReplaySubject to it ***//
      //*****************************************************************//

      NewsHeadlineFeed NewsFeed2 = new NewsHeadlineFeed("Headline News Feed #2");
      NewsFeed2.HeadlineFeed.Timestamp().Subscribe(myReplaySubject);


      //*****************************************************************************************************//
      //*** Create a subscription to the subject's observable sequence. This subscription will filter for ***//
      //*** only local headlines that occurred 10 seconds before the subscription was created.            ***//
      //***                                                                                               ***//
      //*** Since we are using a ReplaySubject with timestamped headlines, we can subscribe to the        ***//
      //*** headlines already past. The ReplaySubject will "replay" them for the localNewSubscription     ***//
      //*** from its buffered sequence of headlines.                                                      ***//
      //*****************************************************************************************************//

      Console.WriteLine("Waiting for 10 seconds before subscribing to local news headline feed.\n");
      Thread.Sleep(10000);

      Console.WriteLine("\n*** Creating local news headline subscription at {0} ***\n", DateTime.Now.ToString());
      Console.WriteLine("This subscription asks the ReplaySubject for the buffered headlines that\n" +
                        "occurred within the last 10 seconds.\n\nPress ENTER to exit.", DateTime.Now.ToString());

      DateTime lastestHeadlineTime = DateTime.Now;
      DateTime earliestHeadlineTime = lastestHeadlineTime - TimeSpan.FromSeconds(10);     
      
      IDisposable localNewsSubscription = myReplaySubject.Where(x => x.Value.Contains("in your area.") &&
                                                               (x.Timestamp >= earliestHeadlineTime) &&
                                                               (x.Timestamp < lastestHeadlineTime)).Subscribe(x =>
      {
        Console.WriteLine("\n************************************\n" +
                          "***[ Local news headline report ]***\n" +
                          "************************************\n" + 
                          "Time         : {0}\n{1}\n\n", x.Timestamp.ToString(), x.Value);
      });

      Console.ReadLine();


      //*******************************//
      //*** Cancel the subscription ***//
      //*******************************//

      localNewsSubscription.Dispose();


      //*************************************************************************//
      //*** Unsubscribe all the ReplaySubject's observers and free resources. ***//
      //*************************************************************************//

      myReplaySubject.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(3000)); 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)];
    }
  }
}

下列輸出是使用範例程式碼所產生。 新的摘要是隨機的,因此您可能必須多次執行它,才能看到當地新聞標題。

Waiting for 10 seconds before subscribing to local news headline feed.

** 在 2011 年 5 月 9 日上午 4:07:48 建立當地新聞頭條訂閱 **

This subscription asks the ReplaySubject for the buffered headlines that
occurred within the last 10 seconds.

Press ENTER to exit.

********************************** [ 本機新聞標題報告 ]**********************************時間:2011 年 5 月 9 日上午 4:07:42 -04:00 摘要名稱:標題新聞摘要 #2 標題:我們在您的區域中有一位優勝者。

********************************** [ 本機新聞標題報告 ]**********************************時間:2011 年 5 月 9 日上午 4:07:47 -04:00 摘要名稱:頭條新聞摘要 #1 標題:區域中發出的雪雨天氣watch。

另請參閱

參考

ReplaySubject < T > 類別

ReplaySubject < T > 多載

System.Reactive.Subjects 命名空間