Retrofit, general type of call

Sorry if my headline is so vague, but I could not find a better one.

I rest Api, which provides the service as follows: /api/{type}/{id}4 'type' and, therefore, 4 types of classes that are returned.

All of these classes apply to the same SuperClass.

My problem is that I seem to always need to explicitly specify the return class:

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

etc...

so now i do

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;
}

who feels completely wrong.

Do you have a way to do it better, maybe something with generics?

Thanks,

+4
source share
1 answer

, 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, .

0

Source: https://habr.com/ru/post/1629030/


All Articles