我已经创建了Call<T>
的自定义实现,这里是没有自定义代码的自定义类,只是您要查看的转发代码。
public class CachedCall<T> implements Call<T> {
private final Call<T> delegate;
public CachedCall(Call<T> delegate) {
this.delegate = delegate;
}
@Override
public Response<T> execute() throws IOException {
return delegate.execute();
}
@Override
public void enqueue(Callback<T> callback) {
delegate.enqueue(callback);
}
public void enqueueWithCache(final CachedCallback<T> callback) {
delegate.enqueue(callback);
}
@Override
public boolean isExecuted() {
return delegate.isExecuted();
}
@Override
public void cancel() {
delegate.cancel();
}
@Override
public boolean isCanceled() {
return delegate.isCanceled();
}
@Override
public Call<T> clone() {
return new CachedCall<>(delegate.clone());
}
@Override
public Request request() {
return delegate.request();
}
}
然后在我的ApiService中,我在我的一些调用中使用了这个自定义实现,而在其他调用中使用了默认实现,例如:
public interface APIService {
@GET("categories")
Call<List<Categorie>> categories(@Query("tag") String tag);
@GET("categories/{categorie}/quotes")
CachedCall<List<Gif>> gifs(@Path("categorie") String categorie);
当调用自定义方法时,我遇到了崩溃:
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for CustomClass.
Tried:
* retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
* retrofit2.ExecutorCallAdapterFactory
at retrofit2.Retrofit.nextCallAdapter(Retrofit.java:237)
at retrofit2.Retrofit.callAdapter(Retrofit.java:201)
at retrofit2.ServiceMethod$Builder.createCallAdapter(ServiceMethod.java:232)
... 21 more
我是否需要在某处使用Retrofit注册我的自定义实现?
答案 0 :(得分:1)
我已经解决了自己的问题。
您需要创建并注册自己的CallAdapter.Factory:
public class CachedCallAdapterFactory extends CallAdapter.Factory {
final Executor callbackExecutor;
public CachedCallAdapterFactory(Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
@Override
public CallAdapter<Call<?>> get(final Type returnType, final Annotation[] annotations, final Retrofit retrofit) {
if (getRawType(returnType) != CachedCall.class) {
return null;
}
final Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
return new CallAdapter<Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public <R> Call<R> adapt(Call<R> call) {
return new CachedCall<>(callbackExecutor, call, responseType, retrofit, annotations);
}
};
}
}
然后在创建Retrofit实例时注册它:
retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(URL)
.addCallAdapterFactory(new CachedCallAdapterFactory(new DefaultExecutor()))
.build();
您的DefaultExecutor
只需要运行其Runnable
private class DefaultExecutor implements Executor {
@Override
public void execute(@NonNull Runnable runnable) {
runnable.run();
}
}