All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.octo.android.robospice.retrofit.RetrofitSpiceService Maven / Gradle / Ivy

package com.octo.android.robospice.retrofit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import retrofit.RestAdapter;
import retrofit.converter.Converter;

import com.octo.android.robospice.SpiceService;
import com.octo.android.robospice.request.CachedSpiceRequest;
import com.octo.android.robospice.request.listener.RequestListener;
import com.octo.android.robospice.request.retrofit.RetrofitSpiceRequest;

public abstract class RetrofitSpiceService extends SpiceService {

    private Map, Object> retrofitInterfaceToServiceMap = new HashMap, Object>();
    private RestAdapter.Builder builder;
    private RestAdapter restAdapter;
    protected List> retrofitInterfaceList = new ArrayList>();
    private Converter mConverter;

    @Override
    public void onCreate() {
        super.onCreate();
        builder = createRestAdapterBuilder();
        restAdapter = builder.build();
    }

    protected abstract String getServerUrl();

    protected RestAdapter.Builder createRestAdapterBuilder() {
        return new RestAdapter.Builder().setEndpoint(getServerUrl()).setConverter(getConverter());
    }

    protected abstract Converter createConverter();

    protected final Converter getConverter() {
        if (mConverter == null) {
            mConverter = createConverter();
        }

        return mConverter;
    }

    @SuppressWarnings("unchecked")
    protected  T getRetrofitService(Class serviceClass) {
        T service = (T) retrofitInterfaceToServiceMap.get(serviceClass);
        if (service == null) {
            service = restAdapter.create(serviceClass);
            retrofitInterfaceToServiceMap.put(serviceClass, service);
        }
        return service;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void addRequest(CachedSpiceRequest request, Set> listRequestListener) {
        if (request.getSpiceRequest() instanceof RetrofitSpiceRequest) {
            RetrofitSpiceRequest retrofitSpiceRequest = (RetrofitSpiceRequest) request.getSpiceRequest();
            retrofitSpiceRequest.setService(getRetrofitService(retrofitSpiceRequest.getRetrofitedInterfaceClass()));
        }
        super.addRequest(request, listRequestListener);
    }

    public final List> getRetrofitInterfaceList() {
        return retrofitInterfaceList;
    }

    protected void addRetrofitInterface(Class serviceClass) {
        retrofitInterfaceList.add(serviceClass);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy