问题
I'm trying to figure out how to "restart" an IConnectableObservable
after it has completed or errored.
The code below shows two subscribers (A, B) to a connnectable observable. Once their subscription is disposed, a new subscriber (C) connects. I'd like it to appear to C that it is an entirely new observable, but I am only getting the exception raised in the first subscription.
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();
}
gives the following result:
A: msg
B: msg
A: System.Exception: boom
B: System.Exception: boom
Observer has unsubscribed
C: System.Exception: boom
Observer has unsubscribed
whereas I would like:
A: msg
B: msg
A: System.Exception: boom
B: System.Exception: boom
Observer has unsubscribed
C: msg
C: System.Exception: boom
Observer has unsubscribed
Any ideas? Thanks!
回答1:
While it doesn't "restart" the observable, replacing Publish
with Replay provides the output you are expecting. However, keep in mind this will buffer all of the values from the source observable. It's best to put a limit on the number of replayed values.
来源:https://stackoverflow.com/questions/47739717/is-it-possible-to-restart-an-iconnectableobservable