menefrego
menefrego

Reputation: 115

How to retry a stream in RxDart?

I'm quite a newcomer in Dart and Flutter and I'm facing an obstacle.

I'm developing an app in flutter, which uses network calls, token auth etc. I use Dio and RxDart. The problem is that by default I need to retry every api call 5 times until I get a proper response from a server (e.g when I make call for a token server responses 202 for a first call and 200 for a second or third call). How can I retry a call?

Here's my GET method:

  Future _get(String url, {Map<String, dynamic> headers}) async {
    var response = await dio.get(url, options:
    new Options(headers: headers));
    return response.data;
  }

and a method which returns Future Observable:

 Observable get2(String url, {Map<String, dynamic> headers}) {
return Observable.retry(_sourceStream(url, headers: headers) , 5);

}

 Stream Function() _sourceStream(String url, {Map<String, dynamic> headers}) {
return  () => Observable.fromFuture(_get(url, headers: headers));

}

I know that there's a retryWhen factory method in RxDart, but I was unable to use it in a proper way with my methods. Can anyone help?

Upvotes: 2

Views: 2150

Answers (1)

Adelina
Adelina

Reputation: 11881

With Observable.retry:

Observable.retry(() => Observable.fromFuture(_get(url, headers: headers)), 5)

With RetryWhenStream:

    int retries = 0;
    RetryWhenStream(
      () => Observable.fromFuture(_get(url, headers: headers))),
      (e, s) {
        retries+=1;
        // if there is more than 5 retries, throw an error
        if (retries <= 5) return Observable.just('Lets retry again');
        return Observable.error(e);
      },
    );

It will start to retry 5 times(if there is an error) when someone starts to listen to these streams

Upvotes: 3

Related Questions