Skip to content

Commit

Permalink
Note that the callback executor should be used when non-null.
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeWharton committed Mar 2, 2016
1 parent 4ebe52c commit 3620ef5
Showing 1 changed file with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.Executor;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
Expand Down Expand Up @@ -68,13 +69,14 @@ public static class ErrorHandlingCallAdapterFactory extends CallAdapter.Factory
"MyCall must have generic type (e.g., MyCall<ResponseBody>)");
}
final Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
final Executor callbackExecutor = retrofit.callbackExecutor();
return new CallAdapter<MyCall<?>>() {
@Override public Type responseType() {
return responseType;
}

@Override public <R> MyCall<R> adapt(Call<R> call) {
return new MyCallAdapter<>(call);
return new MyCallAdapter<>(call, callbackExecutor);
}
};
}
Expand All @@ -83,9 +85,11 @@ public static class ErrorHandlingCallAdapterFactory extends CallAdapter.Factory
/** Adapts a {@link Call} to {@link MyCall}. */
static class MyCallAdapter<T> implements MyCall<T> {
private final Call<T> call;
private final Executor callbackExecutor;

MyCallAdapter(Call<T> call) {
MyCallAdapter(Call<T> call, Executor callbackExecutor) {
this.call = call;
this.callbackExecutor = callbackExecutor;
}

@Override public void cancel() {
Expand All @@ -95,6 +99,9 @@ static class MyCallAdapter<T> implements MyCall<T> {
@Override public void enqueue(final MyCallback<T> callback) {
call.enqueue(new Callback<T>() {
@Override public void onResponse(Call<T> call, Response<T> response) {
// TODO if 'callbackExecutor' is not null, the 'callback' methods should be executed
// on that executor by submitting a Runnable. This is left as an exercise for the reader.

int code = response.code();
if (code >= 200 && code < 300) {
callback.success(response);
Expand All @@ -110,6 +117,9 @@ static class MyCallAdapter<T> implements MyCall<T> {
}

@Override public void onFailure(Call<T> call, Throwable t) {
// TODO if 'callbackExecutor' is not null, the 'callback' methods should be executed
// on that executor by submitting a Runnable. This is left as an exercise for the reader.

if (t instanceof IOException) {
callback.networkError((IOException) t);
} else {
Expand All @@ -120,7 +130,7 @@ static class MyCallAdapter<T> implements MyCall<T> {
}

@Override public MyCall<T> clone() {
return new MyCallAdapter<>(call.clone());
return new MyCallAdapter<>(call.clone(), callbackExecutor);
}
}

Expand Down

0 comments on commit 3620ef5

Please sign in to comment.