作者:D调肥仔 | 来源:互联网 | 2023-02-01 23:34
我是RX的新手,一直在研究错误处理和Retry的使用。我有以下内容(是的,我知道这不是一个“真实的”单元测试,但是它给了我一些摆弄的地方!),我想知道如何继续重试,但是能够记录任何异常?
[Test]
public void Test()
{
var scheduler = new TestScheduler();
var source = scheduler.CreateHotObservable(
new Recorded>(10000000, Notification.CreateOnNext(0L)),
new Recorded>(20000000, Notification.CreateOnNext(1L)),
new Recorded>(30000000, Notification.CreateOnNext(2L)),
new Recorded>(30000001, Notification.CreateOnError(new Exception("Fail"))),
new Recorded>(40000000, Notification.CreateOnNext(3L)),
new Recorded>(40000000, Notification.CreateOnCompleted())
);
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?
谢谢!
1> Shlomo..:
您可以这样实现:
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
显示两次,因为每次您订阅时都会显示一次(该Retry
操作在OnError
。之后。
坦率地说,您的测试是一个不好的测试。它违反了“ Rx合同”,即通知遵循以下模式:
OnNext* (OnCompleted | OnError)?
也就是说,0个或多个OnNext
通知,后跟一个可选OnError
或可选的OnCompleted
。任何类型的通知都不得在OnError
或之后OnCompleted
。