如何扩展 Retrofit 2.0 调用? [英] How can I extend a Retrofit 2.0 Call?
本文介绍了如何扩展 Retrofit 2.0 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现这样的目标:
MyCall<MyResponse> call = service.login(loginRequest);
call.enqueue(
new Runnable() {
@Override
public void run() {
// onResponse
}
}, new Runnable() {
@Override
public void run() {
// onFailure
}
});
这样当我必须拨打电话时,我不需要解析每个回调中的响应,并且代码更轻巧且可重用.
so that when I have to make a call I don't need to parse the response in each callback and the code is a little lighter and reusable.
我尝试了此代码段中的代码,但出现错误:
I tried the code from this snippet but I get the error:
无法为 XXXX 创建呼叫适配器.
我错过了什么?
推荐答案
我没有扩展 Call
但我扩展了 Callback
,这也有助于使 代码更轻巧且可重用.
I did not extend Call
but I extend Callback
, it's also help to make the code is a little lighter and reusable.
public abstract class CustomCallback<T> implements Callback<T> {
@Override
public void onResponse(final Response<T> response, Retrofit retrofit) {
Runnable runnable = new Runnable() {
@Override
public void run() {
onRequestSuccess(response);
}
};
runnable.run();
}
@Override
public void onFailure(final Throwable t) {
Runnable runnable = new Runnable() {
@Override
public void run() {
onRequestFail(t);
}
};
runnable.run();
}
public abstract void onRequestSuccess(Response<T> response);
public abstract void onRequestFail(Throwable t);
}
然后当你调用 enqueue()
时:
call.enqueue(new CustomCallback<YourObject>() {
@Override
public void onRequestSuccess(final Response<YourObject> response)
{
}
@Override
public void onRequestFail(final Throwable t) {
}
});
希望对你有帮助
这篇关于如何扩展 Retrofit 2.0 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文