/
CallbackRunnable.java
40 lines (35 loc) · 1.17 KB
/
CallbackRunnable.java
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
// Copyright 2012 Square, Inc.
package retrofit.http;
import java.util.concurrent.Executor;
/**
* A {@link Runnable} executed on a background thread to invoke {@link #obtainResponse()} which
* performs an HTTP request. The response of the request, whether it be an object or exception, is
* then marshaled to the supplied {@link Executor} in the form of a method call on a
* {@link Callback}.
*/
abstract class CallbackRunnable<T> implements Runnable {
private final Callback<T> callback;
private final Executor callbackExecutor;
CallbackRunnable(Callback<T> callback, Executor callbackExecutor) {
this.callback = callback;
this.callbackExecutor = callbackExecutor;
}
@SuppressWarnings("unchecked")
@Override public final void run() {
try {
final Object response = obtainResponse();
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.success((T) response);
}
});
} catch (final RetrofitError e) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.failure(e);
}
});
}
}
public abstract Object obtainResponse();
}