Как переписать код для модернизации, если я получаю четыре pojo в одном запросе? - PullRequest
0 голосов
/ 26 сентября 2018

У меня есть запрос api rest: api.coinmarketcap.com/v2/ticker/?convert=EUR Как вы можете видеть, здесь один метод "convert = EUR" (не может добавить еще один).Я делаю 4 запроса в одном asyncTask и создаю pojo с помощью gson (я знаю, это плохая практика):

public Currencies fetchItems(int capacity){
        List<Currency> currencyList;

        Uri.Builder uriBuilder = ENDPOINT.buildUpon().appendQueryParameter("limit","" + capacity);
        String uriUsd = uriBuilder.build().toString();
        String uriBtc = uriBuilder.appendQueryParameter("convert", "BTC").build().toString();
        uriBuilder = ENDPOINT.buildUpon().appendQueryParameter("limit","" + capacity);
        String uriRub = uriBuilder.appendQueryParameter("convert", "RUB").build().toString();
        uriBuilder = ENDPOINT.buildUpon().appendQueryParameter("limit","" + capacity);
        String uriEur = uriBuilder.appendQueryParameter("convert", "EUR").build().toString();
        try {
            String jsonString = getUrlString(uriUsd);
            String jsonStringBtc = getUrlString(uriBtc);
            String jsonStringRub = getUrlString(uriRub);
            String jsonStringEur = getUrlString(uriEur);
            Currencies currencies = deserializationCryptoRequest(jsonString);
            Currencies btc = deserializationCryptoRequest(jsonStringBtc);
            Currencies rub = deserializationCryptoRequest(jsonStringRub);
            Currencies eur = deserializationCryptoRequest(jsonStringEur);
            currencyList = new ArrayList<>(currencies.getData().values());
            List<Currency> btcList = new ArrayList<>(btc.getData().values());
            List<Currency> rubList = new ArrayList<>(rub.getData().values());
            List<Currency> eurList = new ArrayList<>(eur.getData().values());

            for(int i = 0; i < currencyList.size(); i++){
                Currency item = currencyList.get(i);
                Currency btcItem = btcList.get(i);
                Currency rubItem = rubList.get(i);
                Currency eurItem = eurList.get(i);
                String bitmapPath = IconsManager.getIconsLinks().get(item.getSymbol());
                item.setIconBitmap(downloadBitmap(bitmapPath));
                item.addQoute("BTC", btcItem.getQuotes().get("BTC"));
                item.addQoute("RUB", rubItem.getQuotes().get("RUB"));
                item.addQoute("EUR", eurItem.getQuotes().get("EUR"));
            }
             return currencies;
        } catch (IOException ioe){
            Log.e(TAG, "Cannot get response from api: " + ioe);
        }
        return null;
    }

Я сделал это, чтобы сохранить несколько преобразований в памяти.Как я могу сделать это с помощью Retrofit?Как сделать более элегантно?

1 Ответ

0 голосов
/ 26 сентября 2018

определить ваш baseurl:

public class Constants {
    public static final String BASE_URL = "https://api.coinmarketcap.com/v2/";
}

создать интерфейс клиента для модификации:

import io.reactivex.Single;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface CoinMarketClient {
@GET("listings")
Single<CoinMarketListingsReponse> getListings();

@GET("ticker/{id}")
Single<CoinMarketCurrencyResponse> getCurrency(@Path("id") int id);

@GET("ticker/{id}/?convert={fiat}")
Single<CoinMarketCurrencyResponse> getCurrency(@Path("id") int id, 
@Path("fiat") String fiatCode);
}

создать перечисление:

public enum FiatCode {
AUD,
BRL,
CAD,
CHF,
CLP,
CNY,
CZK,
DKK,
EUR,
GBP,
HKD,
HUF,
IDR,
ILS,
INR,
JPY,
KRW,
MXN,
MYR,
NOK,
NZD,
PHP,
PKR,
PLN,
RUB,
SEK,
SGD,
THB,
TRY,
TWD,
USD,
ZAR
}

инициализировать вещи для модификации:

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new 
    OkHttpClient.Builder().addInterceptor(interceptor).build();

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Quotes.class, new QuotesDeserializer())
            .create();

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson));

    Retrofit retrofit = builder.build();

    coinMarketClient = retrofit.create(CoinMarketClient.class);
...