订阅 Observable.Retry() 直到完成才返回? [英] Subscribe to Observable.Retry() doesn't return until it completes?

查看:46
本文介绍了订阅 Observable.Retry() 直到完成才返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 IObservable.Subscribe 是异步的:无论内部发生什么,我都希望恢复订阅.

I expect IObservable.Subscribe to be asynchronous: whatever happens inside, I would like my subscription back.

但是 Retry 似乎有不同的语义:

But Retry seems to have a different semantic:

var retry = Observable.Throw(new Exception(), 0).Retry();
Console.WriteLine("got here");
var subscription = retry.Subscribe();
Console.WriteLine("didn't get here, ever");

这里显然有一些我不明白的地方.我猜想使用不带参数的Retry不能经常使用,或者应该用于我没有想到的东西.

There is clearly something I don't understand here. I guess using Retry with no parameters can't be used very often, or it should be used for something that I haven't thought of.

推荐答案

问题与 Retry 无关 - 它是 Observable.Throw 因为它默认为在立即调度程序上调度它的 OnError.把你的第一行改成这样,你就是金子了:

The problem isn't anything to do with Retry - it's Observable.Throw because it defaults to scheduling its OnError on the immediate scheduler. Change your first line to this and you are golden:

var retry = Observable.Throw<int>(new Exception(), Scheduler.Default).Retry();

一般来说,Rx 会尝试使用它所能使用的最直接的调度程序.Scheduler.Default 将使用当前平台的首选调度器,引入并发.

In general Rx tries to use the most immediate scheduler it can. Scheduler.Default will use the current platform's preferred scheduler that introduces concurrency.

Retry 将首先订阅当前线程(这很好),然后订阅 Throw 终止的任何线程上的每次重试.

Retry will initially subscribe on the current thread (which is fine) and then subscribe for each retry on whatever thread Throw terminates on.

编辑

虽然上述修复有效 - 这可能不是最好的方法.ThrowRetry 尝试使用立即调度程序实际上很好,因为这是计算效率最高的方法.上面的代码将导致 Throw每次迭代在不同的线程上运行.

Although the fix above works - it's probably not the best way. It's actually good that Throw and Retry try to use the immediate scheduler as this is the most computationally efficient way. The code above will cause every iteration of Throw to run on a different thread.

更好、更惯用的 Rx 解决方案是编辑第三行:

A better and more idiomatic Rx solution would be to edit the third line instead:

var subscription = retry.SubscribeOn(Scheduler.Default).Subscribe();

这只会导致对 Retry 的初始订阅在不同的线程上异步发生 - 其余处理将保留在该线程上.

This causes only the initial subscription to Retry to happen asynchronously on a different Thread - and the rest of the processing will stay on that one thread.

这篇关于订阅 Observable.Retry() 直到完成才返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆