|
12 | 12 | import android.widget.ListView; |
13 | 13 |
|
14 | 14 | import com.morihacky.android.rxjava.R; |
| 15 | +import com.morihacky.android.rxjava.RxUtils; |
15 | 16 |
|
16 | 17 | import java.util.ArrayList; |
17 | 18 | import java.util.List; |
| 19 | +import java.util.Locale; |
18 | 20 | import java.util.concurrent.TimeUnit; |
19 | 21 |
|
20 | 22 | import butterknife.Bind; |
21 | 23 | import butterknife.ButterKnife; |
22 | 24 | import butterknife.OnClick; |
23 | 25 | import rx.Observable; |
24 | | -import rx.Subscriber; |
25 | 26 | import rx.functions.Action0; |
26 | 27 | import rx.functions.Action1; |
27 | | -import rx.schedulers.Schedulers; |
| 28 | +import rx.functions.Func1; |
28 | 29 | import rx.subscriptions.CompositeSubscription; |
29 | 30 | import timber.log.Timber; |
30 | 31 |
|
31 | 32 | public class PollingFragment |
32 | 33 | extends BaseFragment { |
33 | 34 |
|
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 | + |
36 | 39 | @Bind(R.id.list_threading_log) ListView _logsList; |
37 | 40 |
|
38 | 41 | private LogAdapter _adapter; |
39 | 42 | private List<String> _logs; |
40 | | - private CompositeSubscription _subscriptions; |
| 43 | + private CompositeSubscription _subscriptions = new CompositeSubscription(); |
41 | 44 | private int _counter = 0; |
42 | 45 |
|
43 | | - @Override |
44 | | - public void onDestroy() { |
45 | | - super.onDestroy(); |
46 | | - _subscriptions.unsubscribe(); |
47 | | - } |
48 | | - |
49 | 46 | @Override |
50 | 47 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { |
51 | 48 | super.onActivityCreated(savedInstanceState); |
52 | | - _subscriptions = new CompositeSubscription(); |
53 | 49 | _setupLogger(); |
54 | 50 | } |
55 | 51 |
|
@@ -62,35 +58,138 @@ public View onCreateView(LayoutInflater inflater, |
62 | 58 | return layout; |
63 | 59 | } |
64 | 60 |
|
| 61 | + @Override |
| 62 | + public void onDestroy() { |
| 63 | + super.onDestroy(); |
| 64 | + RxUtils.unsubscribeIfNotNull(_subscriptions); |
| 65 | + ButterKnife.unbind(this); |
| 66 | + } |
| 67 | + |
65 | 68 | @OnClick(R.id.btn_start_simple_polling) |
66 | 69 | 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 | + ); |
85 | 123 | } |
86 | 124 |
|
87 | 125 | // ----------------------------------------------------------------------------------- |
88 | | - // Method that help wiring up the example (irrelevant to RxJava) |
89 | 126 |
|
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; |
91 | 142 |
|
| 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) { |
92 | 184 | 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 | + |
94 | 193 | } catch (InterruptedException e) { |
95 | 194 | Timber.d("Operation was interrupted"); |
96 | 195 | } |
@@ -99,6 +198,12 @@ private String _doNetworkCallAndGetStringResult() { |
99 | 198 | return String.valueOf(_counter); |
100 | 199 | } |
101 | 200 |
|
| 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 | + |
102 | 207 | private void _log(String logMsg) { |
103 | 208 | if (_isCurrentlyOnMainThread()) { |
104 | 209 | _logs.add(0, logMsg + " (main thread) "); |
@@ -120,9 +225,10 @@ public void run() { |
120 | 225 | } |
121 | 226 |
|
122 | 227 | private void _setupLogger() { |
123 | | - _logs = new ArrayList<String>(); |
| 228 | + _logs = new ArrayList<>(); |
124 | 229 | _adapter = new LogAdapter(getActivity(), new ArrayList<String>()); |
125 | 230 | _logsList.setAdapter(_adapter); |
| 231 | + _counter = 0; |
126 | 232 | } |
127 | 233 |
|
128 | 234 | private boolean _isCurrentlyOnMainThread() { |
|