GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ref: use RepeatWhen approach for increasingly delayed polling · fmlking/RxJava-Android-Samples@87124aa

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • README.md
  • app/src/main/java/com/morihacky/android/rxjava/fragments
    • PollingFragment.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎README.md‎

Copy file name to clipboardExpand all lines: README.md
+13Lines changed: 13 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,17 @@ While the example here is pretty rudimentary, the technique used to achieve the
7070

7171
This is an example of polling using RxJava Schedulers. This is useful in cases, where you want to constantly poll a server and possibly get new data. The network call is "simulated" so it forces a delay before return a resultant string.
7272

73+
There are two variants for this:
74+
75+
1. Simple Polling: say when you want to execute a certain task every 5 seconds
76+
2. Increasing Delayed Polling: say when you want to execute a task first in 1 second, then in 2 seconds, then 3 and so on.
77+
78+
The second example is basically a variant of [Exponential Backoff](https://github.com/kaushikgopal/RxJava-Android-Samples#exponential-backoff).
79+
80+
Instead of using a RetryWithDelay, we use a RepeatWithDelay here. To understand the difference between Retry(When) and Repeat(When) I wouuld suggest Dan's [fantastic post on the subject](http://blog.danlew.net/2016/01/25/rxjavas-repeatwhen-and-retrywhen-explained/).
81+
82+
An alternative approach to delayed polling without the use of `repeatWhen` would be using chained nested delay observables. See [startExecutingWithExponentialBackoffDelay in the ExponentialBackOffFragment example](https://github.com/kaushikgopal/RxJava-Android-Samples/blob/master/app/src/main/java/com/morihacky/android/rxjava/fragments/ExponentialBackoffFragment.java#L111).
83+
7384
### RxBus - An event bus using RxJava + DebouncedBuffer
7485

7586
Have a look at the accompanying blog posts for details on this demo:
@@ -132,6 +143,8 @@ We simulate this behaviour using RxJava with the [`retryWhen` operator](http://r
132143
* http://stackoverflow.com/a/25292833/159825
133144
* Another excellent implementation via @[sddamico](https://github.com/sddamico) : https://gist.github.com/sddamico/c45d7cdabc41e663bea1
134145

146+
Also look at the [Polling example](https://github.com/kaushikgopal/RxJava-Android-Samples#polling-with-schedulers) where we use a very similar Exponential backoff mechanism.
147+
135148
#### "Repeat" with exponential backoff
136149

137150
Another variant of the exponential backoff strategy is to execute an operation 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.
Collapse file

‎app/src/main/java/com/morihacky/android/rxjava/fragments/PollingFragment.java‎

Copy file name to clipboardExpand all lines: app/src/main/java/com/morihacky/android/rxjava/fragments/PollingFragment.java
+88-46Lines changed: 88 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -16,41 +16,35 @@
1616

1717
import java.util.ArrayList;
1818
import java.util.List;
19+
import java.util.Locale;
1920
import java.util.concurrent.TimeUnit;
2021

2122
import butterknife.Bind;
2223
import butterknife.ButterKnife;
2324
import butterknife.OnClick;
2425
import rx.Observable;
25-
import rx.Scheduler;
26-
import rx.Subscriber;
27-
import rx.Subscription;
2826
import rx.functions.Action0;
2927
import rx.functions.Action1;
3028
import rx.functions.Func1;
31-
import rx.schedulers.Schedulers;
3229
import rx.subscriptions.CompositeSubscription;
3330
import timber.log.Timber;
3431

3532
public class PollingFragment
3633
extends BaseFragment {
3734

38-
public static final int INITIAL_DELAY = 0;
39-
public static final int POLLING_INTERVAL = 500;
35+
private static final int INITIAL_DELAY = 0;
36+
private static final int POLLING_INTERVAL = 1000;
37+
4038
@Bind(R.id.list_threading_log) ListView _logsList;
4139

4240
private LogAdapter _adapter;
4341
private List<String> _logs;
44-
private CompositeSubscription _subscriptions;
42+
private CompositeSubscription _subscriptions = new CompositeSubscription();
4543
private int _counter = 0;
46-
private Scheduler.Worker _worker;
4744

4845
@Override
4946
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
5047
super.onActivityCreated(savedInstanceState);
51-
_subscriptions = new CompositeSubscription();
52-
_worker = Schedulers.newThread()
53-
.createWorker();
5448
_setupLogger();
5549
}
5650

@@ -72,8 +66,6 @@ public void onDestroy() {
7266

7367
@OnClick(R.id.btn_start_simple_polling)
7468
public void onStartSimplePollingClicked() {
75-
_setupLogger();
76-
7769
_subscriptions.add(//
7870
Observable.interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
7971
.map(new Func1<Long, String>() {
@@ -100,44 +92,89 @@ public void call(String s) {
10092
@OnClick(R.id.btn_start_increasingly_delayed_polling)
10193
public void onStartIncreasinglyDelayedPolling() {
10294
_setupLogger();
103-
_log(String.format("Increasingly delayed String polling - %s", _counter));
104-
continueIncreasinglyDelayedPolling(1000, 10);
95+
96+
final int pollingInterval = POLLING_INTERVAL;
97+
final int repeatLimit = 5;
98+
99+
_log(String.format(Locale.US, "Start increasingly delayed polling now time: [xx:%02d]",
100+
_getSecondHand()));
101+
102+
_subscriptions.add(//
103+
Observable.just(1)
104+
.repeatWhen(new RepeatWithDelay(repeatLimit, pollingInterval))
105+
.subscribe(new Action1<Object>() {
106+
@Override
107+
public void call(Object o) {
108+
_log(String.format(Locale.US, "Executing polled task now time : [xx:%02d]",
109+
_getSecondHand()));
110+
}
111+
}, new Action1<Throwable>() {
112+
@Override
113+
public void call(Throwable e) {
114+
Timber.d(e, "arrrr. Error");
115+
}
116+
})
117+
);
105118
}
106119

107-
private void continueIncreasinglyDelayedPolling(final int delay, final int limit) {
108-
_subscriptions = _unsubscribeAndGetNewCompositeSub(_subscriptions);
109-
Observable.create(
110-
new Observable.OnSubscribe<String>() {
111-
@Override
112-
public void call(final Subscriber<? super String> subscriber) {
113-
114-
Subscription subscription = _worker.schedule(new Action0() {
115-
@Override
116-
public void call() {
117-
subscriber.onNext(_doNetworkCallAndGetStringResult());
118-
}
119-
}, delay, TimeUnit.MILLISECONDS);
120-
subscriber.add(subscription);
121-
}
122-
})
123-
.take(limit)
124-
.subscribe(new Action1<String>() {
125-
@Override
126-
public void call(String s) {
127-
continueIncreasinglyDelayedPolling(delay + 1000, limit - 1);
128-
Timber.d("delay of %d", delay);
129-
_log(String.format("String polling - %s", s));
120+
// -----------------------------------------------------------------------------------
121+
122+
// CAUTION:
123+
// --------------------------------------
124+
// THIS notificationHandler class HAS NO BUSINESS BEING non-static
125+
// I ONLY did this cause i wanted access to the `_log` method from inside here
126+
// for the purpose of demonstration. In the real world, make it static and LET IT BE!!
127+
128+
// It's 12am in the morning and i feel lazy dammit !!!
129+
130+
//public static class RepeatWithDelay
131+
public class RepeatWithDelay
132+
implements Func1<Observable<? extends Void>, Observable<?>> {
133+
134+
private final int _repeatLimit;
135+
private final int _pollingInterval;
136+
private int _repeatCount = 1;
137+
138+
RepeatWithDelay(int repeatLimit, int pollingInterval) {
139+
_pollingInterval = pollingInterval;
140+
_repeatLimit = repeatLimit;
141+
}
142+
143+
// this is a notificationhandler, all we care about is
144+
// the emission "type" not emission "content"
145+
// only onNext triggers a re-subscription
146+
147+
@Override
148+
public Observable<?> call(Observable<? extends Void> inputObservable) {
149+
150+
// it is critical to use inputObservable in the chain for the result
151+
// ignoring it and doing your own thing will break the sequence
152+
153+
return inputObservable.flatMap(new Func1<Void, Observable<?>>() {
154+
@Override
155+
public Observable<?> call(Void blah) {
156+
157+
158+
if (_repeatCount >= _repeatLimit) {
159+
// terminate the sequence cause we reached the limit
160+
_log("Completing sequence");
161+
return Observable.empty();
130162
}
131-
});
163+
164+
// since we don't get an input
165+
// we store state in this handler to tell us the point of time we're firing
166+
_repeatCount++;
167+
168+
return Observable.timer(_repeatCount * _pollingInterval,
169+
TimeUnit.MILLISECONDS);
170+
}
171+
});
172+
}
132173
}
174+
133175
// -----------------------------------------------------------------------------------
134176
// Method that help wiring up the example (irrelevant to RxJava)
135177

136-
private static CompositeSubscription _unsubscribeAndGetNewCompositeSub(CompositeSubscription subscription){
137-
RxUtils.unsubscribeIfNotNull(subscription);
138-
return RxUtils.getNewCompositeSubIfUnsubscribed(subscription);
139-
}
140-
141178
private String _doNetworkCallAndGetStringResult() {
142179

143180
try {
@@ -150,6 +187,12 @@ private String _doNetworkCallAndGetStringResult() {
150187
return String.valueOf(_counter);
151188
}
152189

190+
private int _getSecondHand() {
191+
long millis = System.currentTimeMillis();
192+
return (int) (TimeUnit.MILLISECONDS.toSeconds(millis) -
193+
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
194+
}
195+
153196
private void _log(String logMsg) {
154197
if (_isCurrentlyOnMainThread()) {
155198
_logs.add(0, logMsg + " (main thread) ");
@@ -174,7 +217,6 @@ private void _setupLogger() {
174217
_logs = new ArrayList<>();
175218
_adapter = new LogAdapter(getActivity(), new ArrayList<String>());
176219
_logsList.setAdapter(_adapter);
177-
_subscriptions = _unsubscribeAndGetNewCompositeSub(_subscriptions);
178220
_counter = 0;
179221
}
180222

@@ -183,7 +225,7 @@ private boolean _isCurrentlyOnMainThread() {
183225
}
184226

185227
private class LogAdapter
186-
extends ArrayAdapter<String> {
228+
extends ArrayAdapter<String> {
187229

188230
public LogAdapter(Context context, List<String> logs) {
189231
super(context, R.layout.item_log, R.id.item_log, logs);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.