我正在试图找出如何在IConnectableObservable
完成或出错后“重新启动”。
下面的代码显示了一个可连接的可观察对象的两个订阅者(A,B)。一旦他们的订阅被处置,新订户(C)就会连接。我希望C看起来它是一个全新的可观察对象,但我只是在第一个订阅中获得异常。
static void Main(string[] args)
{
var o = Observable.Create<string>(observer =>
{
observer.OnNext("msg");
observer.OnError(new Exception("boom"));
return Disposable.Create(() => {
Console.WriteLine("Observer has unsubscribed");
});
}
)
.Publish();
o.Subscribe(
x => Console.WriteLine("A: " + x),
ex => Console.WriteLine("A: " + ex),
() => Console.WriteLine("A: done"));
o.Subscribe(
x => Console.WriteLine("B: " + x),
ex => Console.WriteLine("B: " + ex),
() => Console.WriteLine("B: done"));
var subscription = o.Connect();
subscription.Dispose();
o.Subscribe(
x => Console.WriteLine("C: " + x),
ex => Console.WriteLine("C: " + ex),
() => Console.WriteLine("C: done"));
subscription = o.Connect();
}
给出以下结果:
A: msg
B: msg
A: System.Exception: boom
B: System.Exception: boom
Observer has unsubscribed
C: System.Exception: boom
Observer has unsubscribed
虽然我想:
A: msg
B: msg
A: System.Exception: boom
B: System.Exception: boom
Observer has unsubscribed
C: msg
C: System.Exception: boom
Observer has unsubscribed
有什么想法吗?谢谢!
答案 0 :(得分:0)
虽然它没有“重新启动”observable,但用Replay
替换Publish
会提供您期望的输出。但是,请记住,这将缓冲源可观察的所有值。最好限制重播值的数量。