forked from paramananda/promise-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromise.java
More file actions
336 lines (290 loc) · 10.8 KB
/
Promise.java
File metadata and controls
336 lines (290 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* The MIT License
*
* Copyright (c) 2017-2018 Paramananda Pradhan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.ppn;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* The Promise object represents the eventual completion (or failure)
* of an asynchronous method calls, and its resulting value.
* <p>
* A Promise is a proxy for a value not necessarily known when
* the promise is created. It allows you to associate handlers
* with an asynchronous action's eventual success value or failure reason.
* This lets asynchronous methods return values like synchronous methods:
* instead of immediately returning the final value,
* the asynchronous method returns a promise to supply the value
* at some point in the future.
* <p>
* For more information on Javascript Promise
* please visit the official Mozilla Promise documentation
*
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</a>
* <p>
* This Android Promise Library slightly different than the native Javascript Promise.
* This promise object has two imprtant method i.e. `resolve()` and `reject()`,
* whenevey you done, your process just call resolve or reject
* function based on resultant value.
* The resultant value will be automatically passed as argument to the
* followng `then()` or `error()` function.
* It supports above JAVA 1.8
*
* Fork me on Github:
* @see <a href="https://github.com/paramananda/promise-java">Open Github Project</a>
*/
public class Promise {
private static final String TAG = "Promise";
private OnSuccessListener onSuccessListener;
private OnErrorListener onErrorListener;
private Promise child;
private boolean isResolved;
private Object resolvedObject;
private Object tag;
public Promise() {
}
public static Promise all(Promise... list) {
Promise p = new Promise();
if (list == null || list.length <= 0) {
Log.w(TAG, "Promise list should not be empty!");
p.resolve(new ArrayList<>());
return p;
}
if (list != null && list.length > 0) {
new Runnable() {
int completedCount = 0;
Object result[] = new Object[list.length];
@Override
public void run() {
for (int i = 0; i < list.length; i++) {
Promise promise = list[i];
promise.setTag(i);
promise.then(res -> {
result[(int) promise.getTag()] = res;
completed(null);
return res;
}).error(err -> completed(err));
}
}
private void completed(Object err) {
completedCount++;
if (err != null) {
p.reject(err);
} else if (completedCount == list.length) {
p.resolve(result);
}
}
}.run();
} else {
Log.w(TAG, "Promises should not be empty!");
p.resolve(new ArrayList<>());
}
return p;
}
public static Promise series(List<?> list, OnSuccessListener listener) {
Promise p = new Promise();
if (list == null || listener == null || list.size() <= 0) {
Log.e(TAG, "Arguments should not be NULL!");
return null;
}
new Runnable() {
int index = -1;
int completedCount = 0;
ArrayList<Object> result = new ArrayList<>(list.size());
@Override
public void run() {
index++;
if (index < list.size()) {
// for (int i = 0; i < list.size(); i++) {
handleSuccess(index, list.get(index));
//}
} else {
p.resolve(result);
}
}
private void handleSuccess(int index, Object object) {
Object res = listener.onSuccess(object);
result.add(index, res);
if (res instanceof Promise) {
Promise pro = (Promise) res;
pro.setTag(index);
pro.then(r -> {
result.set((int) pro.getTag(), r);
if (!completed(null)) {
run();
}
return r;
}).error(err -> completed(err));
} else {
completed(null);
}
}
private boolean completed(Object err) {
completedCount++;
if (err != null) {
p.reject(err);
} else if (completedCount == list.size()) {
p.resolve(result);
return true;
}
return false;
}
}.run();
return p;
}
public static Promise parallel(List<?> list, OnSuccessListener listener) {
Promise p = new Promise();
if (list == null || listener == null || list.size() <= 0) {
Log.e(TAG, "Arguments should not be NULL!");
return null;
}
new Runnable() {
int completedCount = 0;
ArrayList<Object> result = new ArrayList<>(list.size());
@Override
public void run() {
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
handleSuccess(i, list.get(i));
}
} else {
p.resolve(result);
}
}
private void handleSuccess(int index, Object object) {
Object res = listener.onSuccess(object);
result.add(index, res);
if (res instanceof Promise) {
Promise pro = (Promise) res;
pro.setTag(index);
pro.then(r -> {
result.set((int) pro.getTag(), r);
completed(null);
return r;
}).error(err -> completed(err));
} else {
completed(null);
}
}
private void completed(Object err) {
completedCount++;
if (err != null) {
p.reject(err);
} else if (completedCount == list.size()) {
p.resolve(result);
}
}
}.run();
return p;
}
/**
* Call this function with your resultant value, it will be available
* in following `then()` function call.
*
* @param object your resultant value (any type of data you can pass as argument
* e.g. int, String, List, Map, any Java object)
* @return This will return the resultant value you passed in the function call
*/
public Object resolve(Object object) {
isResolved = true;
resolvedObject = object;
handleSuccess(child, object);
return object;
}
/**
* Call this function with your error value, it will be available
* in following `error()` function call.
*
* @param object your error value (any type of data you can pass as argument
* e.g. int, String, List, Map, any Java object)
* @return This will return the error value you passed in the function call
*/
public Object reject(Object object) {
handleError(object);
return object;
}
/**
* After executing asynchronous function the result will be available in the success listener
* as argument.
*
* @param listener OnSuccessListener
* @return It returns a promise for satisfying next chain call.
*/
public Promise then(OnSuccessListener listener) {
onSuccessListener = listener;
child = new Promise();
return child;
}
/**
* This function must call at the end of the `then()` cain, any `reject()` occurs in
* previous async execution this function will be called.
*
* @param listener
*/
public void error(OnErrorListener listener) {
onErrorListener = listener;
}
private void handleSuccess(Promise child, Object object) {
if (onSuccessListener != null) {
Object res = onSuccessListener.onSuccess(object);
if (res != null) {
if (res instanceof Promise) {
if (child != null) {
Promise p = (Promise) res;
p.onSuccessListener = child.onSuccessListener;
p.onErrorListener = child.onErrorListener;
p.child = child.child;
child = p;
}
} else if (child != null) {
child.resolve(res);
}
} else {
if (child != null) {
child.resolve(res);
}
}
}
}
private void handleError(Object object) {
if (onErrorListener != null) {
onErrorListener.onError(object);
} else if (child != null) {
child.reject(object);
}
}
public Object getTag() {
return tag;
}
public void setTag(Object tag) {
this.tag = tag;
}
public interface OnSuccessListener {
Object onSuccess(Object object);
}
public interface OnErrorListener {
void onError(Object object);
}
}