改造,通用呼叫类型

时间:2016-02-16 17:44:37

标签: android retrofit retrofit2

我很抱歉,如果我的头衔太模糊,但我找不到更好的。

我有一个以这种方式公开服务的休息Api:/api/{type}/{id} 4'类型',因此返回4种类型。

所有这些类都来自同一个SuperClass

我的问题是我似乎总是要明确命名返回的类:

Call<Type1> call = apiInterface.get....
Call<Type2> call = apiInterface.get....

等...

所以现在我做

SuperClass object = null;
switch(type){
    case TYPE1:
       Call<Type1> call = apiInterface.getType1(id);
       call.enqueue(new Callback....{
            .......
            object = response.body()
       }
       break;
    case TYPE2:
       Call<Type2> call = apiInterface.getType2(id);
       call.enqueue(new Callback....{
            .......
            object = response.body()
       }
       break;
}
感觉非常错误。

你有办法更好地做到这一点吗,也许是泛型的东西?

谢谢,

1 个答案:

答案 0 :(得分:0)

我最后做的是为我的Api类中的所有子类创建一个包装器:

public Call getCourseElement(Type type, String id){
    Call call = null;
    switch (type) {
        case TYPE1:
            call = apiInterface.getType1(id);
            break;
        case TYPE2:
            call = apiInterface.getType2(id);
            break;
        ...
    }
    return call;
}

并以这种方式使用它:

Call call = api.getCourseElement(type, id);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Response response, Retrofit retrofit) {
                     SuperClass superObj = (SuperClass) response.body()
                     ...........
                }

                @Override
                public void onFailure(Throwable t) {
                     ..........
                }
            });

我有一些未经检查的警告,我仍然有开关。

我想到的另一个解决方案是使用自定义TypeConverter(来自json响应)创建TYPE1 / TYPE2元素并将其发送回SuperClass对象。但我不想测试json,因为它可以轻松改变。

相关问题