为Retrofit创建自定义回调

时间:2015-06-17 07:35:40

标签: android rest callback retrofit

我在我的应用程序中使用Retrofit和Otto进行Web服务调用。我想为每个请求分配一个id,所以我做了一个像这样的自定义Retrofit回调

public class RetrofitCallback<T> implements Callback<T> {

    private static int _idCounter = 1;

    public int requestId;
    private Bus eventBus;

    public RetrofitCallback(Bus eventBus){
        this.requestId = _idCounter;
        this.eventBus = eventBus;
        _idCounter++;
    }

    @Override
    public void success(T data, Response response) {
        // problem.. data is not the type I expected. please see below
        RetrofitRequestSuccess<T> message = new RetrofitRequestSuccess<>(requestId, 
           data, response);
        eventBus.post(message);
    }

    @Override
    public void failure(RetrofitError error) {
        RetrofitRequestFailed message = new RetrofitRequestFailed(requestId, error);
        eventBus.post(message);
    }
}

RetrofitRequestSuccess类

public class RetrofitRequestSuccess<T> {
    public T data;
    public int requestId;
    public Response response;

    public RetrofitRequestSuccess(int requestId, T data, Response response) {
        this.requestId = requestId;
        this.data = data;
        this.response = response;
    }
}

然后我按如下方式使用回调

int requestId = 0; // activity level scope

RestAdapter restApiAdapter = new RestAdapter.Builder().setEndpoint(ENDPOINT).build();
RestAPI restClient = restApiAdapter.create(RestAPI.class);
RetrofitCallback<List<Order>> callback = new RetrofitCallback<>(BusProvider.getBus());
restClient.getOrders(callback);
requestId = callback.requestId;

Otto订阅方法

@Subscribe
public void onHttpResponseReceived(RetrofitRequestSuccess message) {
    if(message.requestId == requestId) {
        List<Order> ordersList = (ArrayList<Order>) message.data;
    }
}

问题是我从未在Order中获得message.data个对象列表。无论我在创建回调时传递的是什么类型,message.data总是包含Gson的LinkedTreeMap对象列表。如何让它返回正确的类型?任何帮助将不胜感激!

0 个答案:

没有答案