RxJS重试()语义(RxJS retry() semantics)

给出.retry()这个例子 :

// Try three times to get the data and then give up var source = get('url').retry(3);

get()返回什么? 有人可以提供实现来使示例工作吗? 即实际重试一些异步代码3次。

我刚刚开始使用RxJS,并且我正在尝试理解语义,并且获得上述示例将非常有用,谢谢!

Given this example for .retry():

// Try three times to get the data and then give up var source = get('url').retry(3);

What does get() return? Can someone provide an implementation to make the example work? i.e. to actually retry some asynchronous code 3 times.

I'm just starting out with RxJS, and am trying to understand the semantics, and getting an example of the above would really help, thanks!

最满意答案

get返回一个Observable 。 retry做法是订阅底层的Observable并捕获onError调用,然后重新订阅Observable同时从下游隐藏onError ,从而防止流终止。 只有Observable要求是它必须“从订阅开始”语义或换句话说是一个冷Observable 。

所以get可以实现为:

function get() { var count = 0; return Rx.Observable.create(function(observer) { if (++count < 2) observer.onError(new Error()); else { observer.onNext("Yay!"); observer.onCompleted(); } }); }

编辑

我重新阅读了你的问题,并认为我误解了你的要求。 我给出的第一个例子只是一个快速的方法,看看如何制作一个可以retry的普通Observable 。 在给出get的场景中,它正在做某种http请求。

以下是使用RxJS-DOM库来执行Ajax请求,但您也可以使用其他具有Promises库。

//With RxJS DOM function get(url) { return Rx.DOM.ajax({url : url}); } //With JQuery Promises function get(url) { return Rx.Observable.defer(function() { return $.ajax(url); }); }

在这两种情况下,您都会遇到一些可能出错的远程服务器资源。 在它之后添加retry将确保问题不是暂时的网络问题。

get returns an Observable. What retry does is it subscribes to the underlying Observable and captures an onError call and then resubscribes to the Observable while hiding the onError from downstream thus keeping the stream from terminating. Only requirement for the Observable is that it must "start on subscribe" semantics or in other words is a cold Observable.

So get could be implemented as:

function get() { var count = 0; return Rx.Observable.create(function(observer) { if (++count < 2) observer.onError(new Error()); else { observer.onNext("Yay!"); observer.onCompleted(); } }); }

Edit

I re-read your question and think I misunderstood what you were asking. The first example I gave is just a quick way of seeing how to make a trivial Observable that will work with retry. In the scenario that is given of get it is doing some sort of http request.

The following is using the RxJS-DOM Library to do the Ajax request but you could use other libraries that have Promises as well.

//With RxJS DOM function get(url) { return Rx.DOM.ajax({url : url}); } //With JQuery Promises function get(url) { return Rx.Observable.defer(function() { return $.ajax(url); }); }

In both cases you are hitting some remote server resource which could potentially error. Adding a retry after it would make sure that the issue is not a transient network issue.

更多推荐