简体   繁体   中英

Is there a 'Hot' equivalent of Observable.Interval

If I do the following:

var obs = 
    Observable
    .Interval(TimeSpan.FromSeconds(1))
    .Select(x => "A" + x.ToString());

obs
.Subscribe(x => Console.WriteLine("From first: " + x.ToString()));

Observable
.Timer(TimeSpan.FromSeconds(3))
.SelectMany(_ => obs)
.Subscribe(x => Console.WriteLine("From second: " + x.ToString()));

I will get this after 4 seconds:

From first:  A0
From first:  A1
From first:  A2
From second: A0
From first:  A3

Is there a 'Hot' equivalent to Observable.Interval that would produce this:

From first:  A0
From first:  A1
From first:  A2
From second: A3
From first:  A3

using Publish() and Connect() will turn your cold observable hot.

var published = Observable
   .Interval(...)
   .Select(...)
   .Publish();

var connectionSubscription = published.Connect();
var observerSubscription = published.Subscribe(...);

Worth noting that the sequence is hot once the Connect() call happens. You can subscribe before the Connect() but make sure you call it at some stage or nothing will ever be observed. There are some alternatives to Connect() eg RefCount() so worth a google. Also worth noting that Publish() returns an IConnectableObservable which provides the Connect() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM