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 — feat: Merge PR #42 courtesy: @marukami · java4ever/RxJava-Android-Samples@75bdc27

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • README.md
  • app/src/main
    • java/com/morihacky/android/rxjava/fragments
      • ExponentialBackoffFragment.java
      • MainFragment.java
      • PollingFragment.java
    • res
      • layout
        • fragment_main.xml
        • fragment_polling.xml
      • values
        • strings.xml
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/ExponentialBackoffFragment.java‎

Copy file name to clipboardExpand all lines: app/src/main/java/com/morihacky/android/rxjava/fragments/ExponentialBackoffFragment.java
+18-6Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ public void startRetryingWithExponentialBackoffStrategy() {
8282
_subscriptions.add(//
8383
Observable//
8484
.error(new RuntimeException("testing")) // always fails
85-
.retryWhen(new RetryWithDelay(5, 1000))//
85+
.retryWhen(new RetryWithDelay(5, 1000)) // notice this is called only onError (onNext values sent are ignored)
8686
.doOnSubscribe(new Action0() {
8787
@Override
8888
public void call() {
@@ -196,7 +196,7 @@ public void run() {
196196

197197
// CAUTION:
198198
// --------------------------------------
199-
// THIS class HAS NO BUSINESS BEING non-static
199+
// THIS notificationHandler class HAS NO BUSINESS BEING non-static
200200
// I ONLY did this cause i wanted access to the `_log` method from inside here
201201
// for the purpose of demonstration. In the real world, make it static and LET IT BE!!
202202

@@ -216,14 +216,24 @@ public RetryWithDelay(final int maxRetries, final int retryDelayMillis) {
216216
_retryCount = 0;
217217
}
218218

219+
// this is a notificationhandler, all that is cared about here
220+
// is the emission "type" not emission "content"
221+
// only onNext triggers a re-subscription (onError + onComplete kills it)
222+
219223
@Override
220-
public Observable<?> call(Observable<? extends Throwable> attempts) {
221-
return attempts.flatMap(new Func1<Throwable, Observable<?>>() {
224+
public Observable<?> call(Observable<? extends Throwable> inputObservable) {
225+
226+
// it is critical to use inputObservable in the chain for the result
227+
// ignoring it and doing your own thing will break the sequence
228+
229+
return inputObservable.flatMap(new Func1<Throwable, Observable<?>>() {
222230
@Override
223231
public Observable<?> call(Throwable throwable) {
224232
if (++_retryCount < _maxRetries) {
233+
225234
// When this Observable calls onNext, the original
226-
// Observable will be retried (i.e. re-subscribed).
235+
// Observable will be retried (i.e. re-subscribed)
236+
227237
Timber.d("Retrying in %d ms", _retryCount * _retryDelayMillis);
228238
_log(String.format("Retrying in %d ms", _retryCount * _retryDelayMillis));
229239

@@ -232,7 +242,9 @@ public Observable<?> call(Throwable throwable) {
232242
}
233243

234244
Timber.d("Argh! i give up");
235-
// Max retries hit. Just pass the error along.
245+
246+
// Max retries hit. Pass an error so the chain is forcibly completed
247+
// only onNext triggers a re-subscription (onError + onComplete kills it)
236248
return Observable.error(throwable);
237249
}
238250
});
Collapse file

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

Copy file name to clipboardExpand all lines: app/src/main/java/com/morihacky/android/rxjava/fragments/MainFragment.java
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ void demoRetrofitCalls() {
5353
clickedOn(new RetrofitFragment());
5454
}
5555

56+
@OnClick(R.id.btn_demo_polling)
57+
void demoPolling() {
58+
clickedOn(new PollingFragment());
59+
}
60+
5661
@OnClick(R.id.btn_demo_double_binding_textview)
5762
void demoDoubleBindingWithPublishSubject() {
5863
clickedOn(new DoubleBindingTextViewFragment());
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
+140-34Lines changed: 140 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,44 +12,40 @@
1212
import android.widget.ListView;
1313

1414
import com.morihacky.android.rxjava.R;
15+
import com.morihacky.android.rxjava.RxUtils;
1516

1617
import java.util.ArrayList;
1718
import java.util.List;
19+
import java.util.Locale;
1820
import java.util.concurrent.TimeUnit;
1921

2022
import butterknife.Bind;
2123
import butterknife.ButterKnife;
2224
import butterknife.OnClick;
2325
import rx.Observable;
24-
import rx.Subscriber;
2526
import rx.functions.Action0;
2627
import rx.functions.Action1;
27-
import rx.schedulers.Schedulers;
28+
import rx.functions.Func1;
2829
import rx.subscriptions.CompositeSubscription;
2930
import timber.log.Timber;
3031

3132
public class PollingFragment
3233
extends BaseFragment {
3334

34-
public static final int INITIAL_DELAY = 0;
35-
public static final int POLLING_INTERVAL = 1000;
35+
private static final int INITIAL_DELAY = 0;
36+
private static final int POLLING_INTERVAL = 1000;
37+
private static final int POLL_COUNT = 8;
38+
3639
@Bind(R.id.list_threading_log) ListView _logsList;
3740

3841
private LogAdapter _adapter;
3942
private List<String> _logs;
40-
private CompositeSubscription _subscriptions;
43+
private CompositeSubscription _subscriptions = new CompositeSubscription();
4144
private int _counter = 0;
4245

43-
@Override
44-
public void onDestroy() {
45-
super.onDestroy();
46-
_subscriptions.unsubscribe();
47-
}
48-
4946
@Override
5047
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
5148
super.onActivityCreated(savedInstanceState);
52-
_subscriptions = new CompositeSubscription();
5349
_setupLogger();
5450
}
5551

@@ -62,35 +58,138 @@ public View onCreateView(LayoutInflater inflater,
6258
return layout;
6359
}
6460

61+
@Override
62+
public void onDestroy() {
63+
super.onDestroy();
64+
RxUtils.unsubscribeIfNotNull(_subscriptions);
65+
ButterKnife.unbind(this);
66+
}
67+
6568
@OnClick(R.id.btn_start_simple_polling)
6669
public void onStartSimplePollingClicked() {
67-
_subscriptions.add(Observable.create(new Observable.OnSubscribe<String>() {
68-
@Override
69-
public void call(final Subscriber<? super String> observer) {
70-
71-
Schedulers.newThread().createWorker() //
72-
.schedulePeriodically(new Action0() {
73-
@Override
74-
public void call() {
75-
observer.onNext(_doNetworkCallAndGetStringResult());
76-
}
77-
}, INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS);
78-
}
79-
}).take(10).subscribe(new Action1<String>() {
80-
@Override
81-
public void call(String s) {
82-
_log(String.format("String polling - %s", s));
83-
}
84-
}));
70+
71+
final int pollCount = POLL_COUNT;
72+
73+
_subscriptions.add(//
74+
Observable.interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
75+
.map(new Func1<Long, String>() {
76+
@Override
77+
public String call(Long heartBeat) {
78+
return _doNetworkCallAndGetStringResult(heartBeat);
79+
}
80+
}).take(pollCount)
81+
.doOnSubscribe(new Action0() {
82+
@Override
83+
public void call() {
84+
_log(String.format("Start simple polling - %s", _counter));
85+
}
86+
})
87+
.subscribe(new Action1<String>() {
88+
@Override
89+
public void call(String taskName) {
90+
_log(String.format(Locale.US, "Executing polled task [%s] now time : [xx:%02d]",
91+
taskName, _getSecondHand()));
92+
}
93+
})
94+
);
95+
}
96+
97+
@OnClick(R.id.btn_start_increasingly_delayed_polling)
98+
public void onStartIncreasinglyDelayedPolling() {
99+
_setupLogger();
100+
101+
final int pollingInterval = POLLING_INTERVAL;
102+
final int pollCount = POLL_COUNT;
103+
104+
_log(String.format(Locale.US, "Start increasingly delayed polling now time: [xx:%02d]",
105+
_getSecondHand()));
106+
107+
_subscriptions.add(//
108+
Observable.just(1)
109+
.repeatWhen(new RepeatWithDelay(pollCount, pollingInterval))
110+
.subscribe(new Action1<Object>() {
111+
@Override
112+
public void call(Object o) {
113+
_log(String.format(Locale.US, "Executing polled task now time : [xx:%02d]",
114+
_getSecondHand()));
115+
}
116+
}, new Action1<Throwable>() {
117+
@Override
118+
public void call(Throwable e) {
119+
Timber.d(e, "arrrr. Error");
120+
}
121+
})
122+
);
85123
}
86124

87125
// -----------------------------------------------------------------------------------
88-
// Method that help wiring up the example (irrelevant to RxJava)
89126

90-
private String _doNetworkCallAndGetStringResult() {
127+
// CAUTION:
128+
// --------------------------------------
129+
// THIS notificationHandler class HAS NO BUSINESS BEING non-static
130+
// I ONLY did this cause i wanted access to the `_log` method from inside here
131+
// for the purpose of demonstration. In the real world, make it static and LET IT BE!!
132+
133+
// It's 12am in the morning and i feel lazy dammit !!!
134+
135+
//public static class RepeatWithDelay
136+
public class RepeatWithDelay
137+
implements Func1<Observable<? extends Void>, Observable<?>> {
138+
139+
private final int _repeatLimit;
140+
private final int _pollingInterval;
141+
private int _repeatCount = 1;
91142

143+
RepeatWithDelay(int repeatLimit, int pollingInterval) {
144+
_pollingInterval = pollingInterval;
145+
_repeatLimit = repeatLimit;
146+
}
147+
148+
// this is a notificationhandler, all we care about is
149+
// the emission "type" not emission "content"
150+
// only onNext triggers a re-subscription
151+
152+
@Override
153+
public Observable<?> call(Observable<? extends Void> inputObservable) {
154+
155+
// it is critical to use inputObservable in the chain for the result
156+
// ignoring it and doing your own thing will break the sequence
157+
158+
return inputObservable.flatMap(new Func1<Void, Observable<?>>() {
159+
@Override
160+
public Observable<?> call(Void blah) {
161+
162+
163+
if (_repeatCount >= _repeatLimit) {
164+
// terminate the sequence cause we reached the limit
165+
_log("Completing sequence");
166+
return Observable.empty();
167+
}
168+
169+
// since we don't get an input
170+
// we store state in this handler to tell us the point of time we're firing
171+
_repeatCount++;
172+
173+
return Observable.timer(_repeatCount * _pollingInterval,
174+
TimeUnit.MILLISECONDS);
175+
}
176+
});
177+
}
178+
}
179+
180+
// -----------------------------------------------------------------------------------
181+
// Method that help wiring up the example (irrelevant to RxJava)
182+
183+
private String _doNetworkCallAndGetStringResult(long attempt) {
92184
try {
93-
Thread.sleep(3000);
185+
if (attempt == 4) {
186+
// randomly make one event super long so we test that the repeat logic waits
187+
// and accounts for this.
188+
Thread.sleep(9000);
189+
} else {
190+
Thread.sleep(3000);
191+
}
192+
94193
} catch (InterruptedException e) {
95194
Timber.d("Operation was interrupted");
96195
}
@@ -99,6 +198,12 @@ private String _doNetworkCallAndGetStringResult() {
99198
return String.valueOf(_counter);
100199
}
101200

201+
private int _getSecondHand() {
202+
long millis = System.currentTimeMillis();
203+
return (int) (TimeUnit.MILLISECONDS.toSeconds(millis) -
204+
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
205+
}
206+
102207
private void _log(String logMsg) {
103208
if (_isCurrentlyOnMainThread()) {
104209
_logs.add(0, logMsg + " (main thread) ");
@@ -120,9 +225,10 @@ public void run() {
120225
}
121226

122227
private void _setupLogger() {
123-
_logs = new ArrayList<String>();
228+
_logs = new ArrayList<>();
124229
_adapter = new LogAdapter(getActivity(), new ArrayList<String>());
125230
_logsList.setAdapter(_adapter);
231+
_counter = 0;
126232
}
127233

128234
private boolean _isCurrentlyOnMainThread() {
Collapse file

‎app/src/main/res/layout/fragment_main.xml‎

Copy file name to clipboardExpand all lines: app/src/main/res/layout/fragment_main.xml
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,11 @@
5252
android:text="@string/btn_demo_double_binding_textview"
5353
/>
5454

55-
<!--<Button
55+
<Button
5656
android:id="@+id/btn_demo_polling"
5757
android:layout_height="wrap_content"
5858
android:layout_width="match_parent"
59-
android:text="@string/btn_demo_polling"
60-
/>-->
59+
android:text="@string/btn_demo_polling" />
6160

6261
<Button
6362
android:id="@+id/btn_demo_rxbus"

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.