2015-04-20 71 views
3

如果我做了以下內容:有沒有「熱」相當於Observable.Interval

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())); 

4秒鐘後,我會得到這樣的:

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

是否有相當於一個「熱」使用發佈()和connect()會變成你的冷觀察到的熱

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

回答

4

Observable.Interval會產生這種。

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

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

值得注意的是,Connect()調用發生後,序列很熱。你可以在Connect()之前訂閱,但要確保你在某個階段調用它,否則什麼都不會被觀察到。 Connect()有一些替代方法,例如RefCount()值得谷歌。另外值得注意的是,Publish()返回提供Connect()調用的IConnectableObservable。

相關問題