其他分享
首页 > 其他分享> > CodeGo.net>有一个“热”等效的Observable.Interval

CodeGo.net>有一个“热”等效的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

是否有一个与Observable.Interval等效的“热”值会产生此结果:

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

解决方法:

使用Publish()和Connect()将使您的冷观测变得很热.

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

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

值得一提的是,一旦发生Connect()调用,序列就很热.您可以在Connect()之前订阅,但请确保在某个阶段调用它,否则将不会观察到任何东西. Connect()有一些替代方法,例如RefCount()非常值得Google使用.还值得注意的是Publish()返回一个IConnectableObservable,它提供了Connect()调用.

标签:system-reactive,c
来源: https://codeday.me/bug/20191028/1952452.html