【问题标题】:How to use retrofit as a singleton while using gson convertor?如何在使用 gson 转换器时将改造用作单例?
【发布时间】:2015-11-03 08:36:53
【问题描述】:

根据@jake Wharton 的回答,您应该只调用一次 restAdapter.create 并在每次需要与之交互时重复使用同一 MyTaskService 实例。 我不能强调这一点。 您可以使用常规单例模式,以确保您在任何地方都只使用这些对象的一个​​实例。依赖注入框架也可以用来管理这些实例,但如果你还没有使用它,那就有点矫枉过正了。

这是我的代码

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();

这让我不得不每次都创建一个新的适配器。在我的应用程序中,一些请求正在并行运行。这是正确的方式吗?

【问题讨论】:

  • 这让我不得不每次都创建一个新的适配器。为什么?
  • @Blackbelt 将 rest 适配器设置为 singleton 后。你将如何将 gson 转换器设置为 restadpater。你会创建一个新的 rest builder 并设置它吗?

标签: java android rest gson retrofit


【解决方案1】:

您不必每次都创建它,而只需在创建 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 将根据您正在调用的改造方法的返回类型调用正确的方法。例如

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

【讨论】:

  • 我有不同的寄存器类型适配器类。示例
  • 我有不同的类型适配器,Gson gson = new GsonBuilder().registerTypeAdapter(GalleryContainer.class, new ExplorerDeserializerJson()) .create();...下次你将如何注册?
  • 您可以多次拨打registerTypeAdapter
  • @当我作为单例时,它将被创建一次..对吗?你将如何改变?除非你创建新的构建器并引用现有对象,当我的请求并行运行时,如果我改变,一切都会好起来的?
  • 如果你需要改变它,你不需要单例。我仍然不明白问题是单例模式还是 Gson
【解决方案2】:

这里是 Singletone RestAdapter & ApiInterface 类的完整代码。如果我们使用 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;
    }

}

ApiInterface 类

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2014-11-07
    • 2018-12-16
    相关资源
    最近更新 更多