使用 gson 转换器时如何将改造用作单例?

How to use retrofit as a singleton while using gson convertor?

From the @jake Wharton answer you should only ever call restAdapter.create once and re-use the same instance of MyTaskService every time you need to interact with. I cannot stress this enough. You can use the regular singleton pattern in order to ensure that there only is ever a single instance of these objects that you use everywhere. A dependency injection framework would also be something that could be used to manage these instances but would be a bit overkill if you are not already utilizing it.

这是我的代码

public class MusicApi {
private static final String API_URL = "https://itunes.apple.com";
private static MusicApiInterface sMusicApiInterface;

public static MusicApiInterface getApi() {
    if (sMusicApiInterface == null) {
        sMusicApiInterface = null;
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();

        sMusicApiInterface = restAdapter.create(MusicApiInterface.class);
    }
    return sMusicApiInterface;
}

public interface MusicApiInterface {
    @GET("/search?entity=musicVideo")
    NetworkResponse getMusic(@Query("term") String term);

    @GET("/search?entity=musicVideo")
    void getMusic(@Query("term") String term, Callback<NetworkResponse> networkResponseCallback);

    @GET("/search?entity=musicVideo")
    Observable<NetworkResponse> getMusicObservable(@Query("term") String term);
}

}

一切正常。我正在使用类型适配器,对于每个请求,我需要创建不同类型的 gson 解析并设置到适配器中。

Gson gson = new GsonBuilder().registerTypeAdapter(DiscussionViewMoreContainer.class, new ExplorerDeserializerJson())
            .create();

这让我每次都必须创建一个新的 restadapter。在我的应用程序中,一些请求是 运行 parallely.is 这种正确的方式?

您不必每次都创建它,只需在创建 RestAdapter 时创建一次即可:

public static MusicApiInterface getApi() {
    if (sMusicApiInterface == null) {
       Gson gson = new GsonBuilder()
           .registerTypeAdapter(DiscussionViewMoreContainer.class, new ExplorerDeserializerJson())
           .create();
       RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(API_URL)
            .setConverter(new GsonConverter(gson))
            .build();
       sMusicApiInterface = restAdapter.create(MusicApiInterface.class);
     }
     return sMusicApiInterface;
}

如果您需要注册多个 Deserializer,只需使用 Class/TypeToken 对和自定义实例 Deserializer 多次调用 .registerTypeAdapter。 Gson 将根据您调用的改造方法的 return 类型调用正确的方法。例如

Gson gson = new GsonBuilder()
           .registerTypeAdapter(DiscussionViewMoreContainer.class, new ExplorerDeserializerJson())
           .registerTypeAdapter(OtherModelClass.class, new OtherModelClassDeserializerJson())
           .registerTypeAdapter(OtherModelClass3.class, new OtherModelClass3DeserializerJson())

这是 Singletone RestAdapter 和 ApiInterface class 的完整代码。如果我们使用 RxAndroid,我们也可以使用 RxJava2CallAdapterFactory。

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import kaj.service.customer.utility.ApplicationData;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by @ShihabMama 20/12/18 5.02 AM :)
 */

public class RestAdapter {

    private static Retrofit retrofit = null;
    private static ApiInterface apiInterface;

    public static ApiInterface getRxClient() {
        if (apiInterface == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(ApplicationData.FINAL_URL)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            apiInterface = retrofit.create(ApiInterface.class);
        }
        return apiInterface;
    }

    public static ApiInterface getApiClient() {
        if (apiInterface == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(ApplicationData.FINAL_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            apiInterface = retrofit.create(ApiInterface.class);
        }
        return apiInterface;
    }

}

Api接口class

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

/**
 * Created by @Shihab_Mama on 11/25/2016.
 */
public interface ApiInterface {

    // TODO: 12/20/2018 sample below
    @GET("orderapi/getOrders?")
    Call<OrderListModel> getOrders(
            @Query("accessToken") String accessToken,
            @Query("companyId") String companyId,
            @Query("customerId") int customerId);

    @POST("orderapi/placeOrder")
    Call<PlaceOrderResponseModel> placeOrder(
            @Query("accessToken") String accessToken,
            @Query("companyId") String companyId,
            @Query("branchId") int branchId,
            @Query("customerId") int customerId,
            @Query("orderNo") String orderNo,
            @Query("orderItemList") String orderItemList,
            @Query("discountedTotalBill") String discountedTotalBill,
            @Query("discountedTotalVat") String discountedTotalVat);

}