retrywhen retry angular rxjs observable

angular - Cómo crear un RXjs RetryWhen con retraso y límite de intentos



rxjs 6 retrywhen (2)

Debe aplicar el límite a la señal de reintento, por ejemplo, si solo quiere 10 reintentos:

loadSomething(): Observable<SomeInterface> { return this.http.get(this.someEndpoint, commonHttpHeaders()) .retryWhen(errors => // Time shift the retry errors.delay(500) // Only take 10 items .take(10) // Throw an exception to signal that the error needs to be propagated .concat(Rx.Observable.throw(new Error(''Retry limit exceeded!'')) ); }

EDITAR

Algunos de los comentaristas preguntaron cómo asegurarse de que el último error es el que se produce. La respuesta es un poco menos clara pero no menos poderosa, solo use uno de los operadores de mapas de aplanamiento (concatMap, mergeMap, switchMap) para verificar en qué índice se encuentra.

Nota: Uso de la nueva sintaxis de pipe RxJS 6 para futuras pruebas (esto también está disponible en versiones posteriores de RxJS 5).

loadSomething(): Observable<SomeInterface> { const retryPipeline = // Still using retryWhen to handle errors retryWhen(errors => errors.pipe( // Use concat map to keep the errors in order and make sure they // aren''t executed in parallel concatMap((e, i) => // Executes a conditional Observable depending on the result // of the first argument iif( () => i > 10, // If the condition is true we throw the error (the last error) throwError(e), // Otherwise we pipe this back into our stream and delay the retry of(e).pipe(delay(500)) ) ) return this.http.get(this.someEndpoint, commonHttpHeaders()) // With the new syntax you can now share this pipeline between uses .pipe(retryPipeline) }

Estoy tratando de hacer una llamada a la API (usando angular4), que reintenta cuando falla, usando reintentar cuando. Quiero que se demore por 500 ms y vuelva a intentarlo. Esto se puede lograr con este código:

loadSomething(): Observable<SomeInterface> { return this.http.get(this.someEndpoint, commonHttpHeaders()) .retryWhen(errors => errors.delay(500)); }

Pero esto seguirá intentando por siempre. ¿Cómo lo limito a, digamos 10 veces?

¡Gracias!