Is it possible to restart an IConnectableObservable?

时光怂恿深爱的人放手 提交于 2021-01-27 21:14:21

问题


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

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