Skip to content

Commit 6a8fea3

Browse files
author
Kaushik Gopal
committed
feat: flush out example that retries with an exponential backoff strategy
1 parent d610fe7 commit 6a8fea3

2 files changed

Lines changed: 86 additions & 5 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ Say you have a network failure. A sensible strategy would be to NOT keep retryin
112112

113113
We simulate this behaviour using RxJava with the `retryWhen`
114114

115+
`RetryWithDelay` code snippet courtesy:
116+
117+
* http://stackoverflow.com/a/25292833/159825
118+
* Another excellent implementation via @[sddamico](https://github.com/sddamico) : https://gist.github.com/sddamico/c45d7cdabc41e663bea1
119+
115120
#### "repeat" with exponential backoff
116121

117122
Another variant of the exponential backoff strategy is to execute an operation repeatedly for a given number of times, but with delayed intervals. So you execute a certain operation 1 second from now, then you execute it again 10 seconds from now, then you execute the operation 20 seconds from now. After a grand total of 3 times you stop executing.

‎app/src/main/java/com/morihacky/android/rxjava/ExponentialBackoffFragment.java‎

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,34 @@ public void onPause() {
6767
public void startRetryingWithExponentialBackoffStrategy() {
6868
_logs = new ArrayList<>();
6969
_adapter.clear();
70-
}
7170

72-
// -----------------------------------------------------------------------------------
71+
_subscriptions.add(//
72+
Observable//
73+
.error(new RuntimeException("testing")) // always fails
74+
.retryWhen(new RetryWithDelay(5, 1000))//
75+
.doOnSubscribe(new Action0() {
76+
@Override
77+
public void call() {
78+
_log("Attempting the impossible 5 times in intervals of 1s");
79+
}
80+
})//
81+
.subscribe(new Observer<Object>() {
82+
@Override
83+
public void onCompleted() {
84+
Timber.d("on Completed");
85+
}
86+
87+
@Override
88+
public void onError(Throwable e) {
89+
_log("Error: I give up!");
90+
}
91+
92+
@Override
93+
public void onNext(Object aVoid) {
94+
Timber.d("on Next");
95+
}
96+
}));
97+
}
7398

7499
@OnClick(R.id.btn_eb_delay)
75100
public void startExecutingWithExponentialBackoffDelay() {
@@ -98,7 +123,7 @@ public Observable<Integer> call(Integer targetSecondDelay) {
98123
.doOnSubscribe(new Action0() {
99124
@Override
100125
public void call() {
101-
_log(String.format("Execute 4 tasks with delay - time now: [xx:%2d]",
126+
_log(String.format("Execute 4 tasks with delay - time now: [xx:%02d]",
102127
_getSecondHand()));
103128
}
104129
})//
@@ -117,8 +142,10 @@ public void onError(Throwable e) {
117142

118143
@Override
119144
public void onNext(Integer integer) {
120-
Timber.d("emitting %d [xx:%2d]", integer, _getSecondHand());
121-
_log(String.format("emitting %d [xx:%2d]", integer, _getSecondHand()));
145+
Timber.d("executing Task %d [xx:%02d]", integer, _getSecondHand());
146+
_log(String.format("executing Task %d [xx:%02d]",
147+
integer,
148+
_getSecondHand()));
122149

123150
}
124151
}));
@@ -132,6 +159,8 @@ private int _getSecondHand() {
132159
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
133160
}
134161

162+
// -----------------------------------------------------------------------------------
163+
135164
private void _setupLogger() {
136165
_logs = new ArrayList<>();
137166
_adapter = new LogAdapter(getActivity(), new ArrayList<String>());
@@ -151,4 +180,51 @@ public void run() {
151180
}
152181
});
153182
}
183+
184+
// -----------------------------------------------------------------------------------
185+
186+
// CAUTION:
187+
// --------------------------------------
188+
// THIS class HAS NO BUSINESS BEING non-static
189+
// I ONLY did this cause i wanted access to the `_log` method from inside here
190+
// for the purpose of demonstration. In the real world, make it static and LET IT BE!!
191+
192+
// It's 12am in the morning and i feel lazy dammit !!!
193+
194+
//public static class RetryWithDelay
195+
public class RetryWithDelay
196+
implements Func1<Observable<? extends Throwable>, Observable<?>> {
197+
198+
private final int _maxRetries;
199+
private final int _retryDelayMillis;
200+
private int _retryCount;
201+
202+
public RetryWithDelay(final int maxRetries, final int retryDelayMillis) {
203+
_maxRetries = maxRetries;
204+
_retryDelayMillis = retryDelayMillis;
205+
_retryCount = 0;
206+
}
207+
208+
@Override
209+
public Observable<?> call(Observable<? extends Throwable> attempts) {
210+
return attempts.flatMap(new Func1<Throwable, Observable<?>>() {
211+
@Override
212+
public Observable<?> call(Throwable throwable) {
213+
if (++_retryCount < _maxRetries) {
214+
// When this Observable calls onNext, the original
215+
// Observable will be retried (i.e. re-subscribed).
216+
Timber.d("Retrying in %d ms", _retryCount * _retryDelayMillis);
217+
_log(String.format("Retrying in %d ms", _retryCount * _retryDelayMillis));
218+
219+
return Observable.timer(_retryCount * _retryDelayMillis,
220+
TimeUnit.MILLISECONDS);
221+
}
222+
223+
Timber.d("Argh! i give up");
224+
// Max retries hit. Just pass the error along.
225+
return Observable.error(throwable);
226+
}
227+
});
228+
}
229+
}
154230
}

0 commit comments

Comments
 (0)