RX.Net:使用重试但记录任何异常

时间:2017-06-06 13:17:07

标签: system.reactive rx.net

我是RX的新手,一直在研究错误处理和Retry的使用;我有以下内容(是的,我知道它不是'真正的'单元测试,但它给了我摆弄的地方!!)并且想知道我如何保持重试但能够记录任何异常?

    [Test]
    public void Test()
    {
        var scheduler = new TestScheduler();

        var source = scheduler.CreateHotObservable(
            new Recorded<Notification<long>>(10000000, Notification.CreateOnNext(0L)),
            new Recorded<Notification<long>>(20000000, Notification.CreateOnNext(1L)),
            new Recorded<Notification<long>>(30000000, Notification.CreateOnNext(2L)),
            new Recorded<Notification<long>>(30000001, Notification.CreateOnError<long>(new Exception("Fail"))),
            new Recorded<Notification<long>>(40000000, Notification.CreateOnNext(3L)),
            new Recorded<Notification<long>>(40000000, Notification.CreateOnCompleted<long>())
        );

        source.Retry().Subscribe(
            l => Console.WriteLine($"OnNext {l}"), 
            exception => Console.WriteLine(exception.ToString()), // Would be logging this in production
            () => Console.WriteLine("OnCompleted"));

       scheduler.Start(
            () => source,
            0,
            TimeSpan.FromSeconds(1).Ticks,
            TimeSpan.FromSeconds(5).Ticks);
    }

导致......

OnNext 0
OnNext 1
OnNext 2
OnNext 3
OnCompleted

...这正是我想要发生的事实,除了事实我想记录2到3之间发生的异常。

是否有办法允许订阅者在OnError中查看异常(并记录它),然后重新订阅以便它看到3?

THX!

1 个答案:

答案 0 :(得分:4)

你可以用这个来实现:

source
    .Do(_ => { }, exception => Console.WriteLine(exception.ToString()), () => {})
    .Retry()
    .Subscribe(
        l => Console.WriteLine($"OnNext {l}"),
        //      exception => Console.WriteLine(exception.ToString()), // Would be logging this in production
        () => Console.WriteLine("OnCompleted")
    );

只是为了澄清这里发生了什么:OnError是一个终止信号。如果错误到达订阅,那将终止流的其余部分。 .Retry终止订阅,吞下OnError,然后重新订阅,将两个订阅合并在一起。例如,看看这个:

source
    .StartWith(-1)
    .Retry()
    .Subscribe(
        l => Console.WriteLine($"OnNext {l}"),
        () => Console.WriteLine("OnCompleted")
    );

您的输出将是

OnNext -1
OnNext 0
OnNext 1
OnNext 2
OnNext -1
OnNext 3
OnCompleted

OnNext -1显示两次,因为它会在您订阅时显示(RetryOnError后执行。

你的测试观察结果坦率地说是一个糟糕的测试。它打破了&#34; Rx合同&#34;这是通知遵循以下模式:

OnNext* (OnCompleted | OnError)? 

即0个或更多OnNext个通知,然后是可选的OnError或可选的OnCompleted。任何类型的通知都不应遵循OnErrorOnCompleted