Is there a 'Hot' equivalent of Observable.Interval

半腔热情 提交于 2019-12-23 19:24:52

问题


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

回答1:


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() e.g. RefCount() so worth a google. Also worth noting that Publish() returns an IConnectableObservable which provides the Connect() call.



来源:https://stackoverflow.com/questions/29751884/is-there-a-hot-equivalent-of-observable-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!