如何取消使用 Rx 调用的异步方法
我想知道如何使用 TakeUntil
取消\停止使用反应式扩展调用的异步方法。
所以我希望能够取消\停止以下方法:
this.booksService.Search(searchText)
.ObserveOnDispatcher()
.Subscribe(results =>
{
this.books.Clear();
this.books.AddRange(results);
});
I want to know how to cancel\stop asynchronous method called using reactive extensions using the TakeUntil
.
So I want to be able to cancel\stop the following method:
this.booksService.Search(searchText)
.ObserveOnDispatcher()
.Subscribe(results =>
{
this.books.Clear();
this.books.AddRange(results);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您处置该值时,
Subscribe()
返回的是一个IDisposable
,如下所示:订阅停止。这真的会阻止底层的图书服务搜索吗?这取决于实施情况。如果使用
Observable.Create
完成,那么很可能会出现这种行为。The return from
Subscribe()
is anIDisposable
, when you dispose the value, like so:the subscription is stopped. Does that actually stop the underlying booksSevice search? That depends on the implementation. If done w/
Observable.Create
then it's quite possible to get that behavior.您必须告诉
booksService
取消搜索。Search
方法启动搜索并返回一个IObservable
。搜索完成后,将在IObservable
上调用OnNext
。Search
中启动了一些异步代码,您需要取消它们。You will have to tell
booksService
to cancel the search. TheSearch
method starts the search and also returns anIObservable
. When the search is completeOnNext
will be called on theIObservable
. There is some asynchronous code started inSearch
that you need to cancel.我的建议是将搜索方法更改为异步调用,该调用将 CancellationToken 作为第二个参数。然后,您可以通过 Observable.ToAsync 将其转换为 Observable 序列。对此可观察量调用 dispose 将触发 CancellationToken 的取消。这样做可以让您轻松地将令牌传递到异步 Web 调用等。
My recommendation is to change the search method to an asynchronous call that takes a CancellationToken as the second argument. You can then convert this to an Observable sequence via Observable.ToAsync. Calling dispose on this observable will then trigger the cancellation of the CancellationToken. Doing this allows you to easily pass the token onto asynchronous web calls etc.