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。在我的应用程序中,一些请求并行运行。这是正确的方法吗?
最佳答案
您不必每次都创建它,只需在创建 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
,只需调用.registerTypeAdapter
多次使用Class/TypeToken
和实例自定义 反序列化器
。 Gson 将根据您调用的 retrofit 方法的返回类型调用正确的方法。例如
Gson gson = new GsonBuilder()
.registerTypeAdapter(DiscussionViewMoreContainer.class, new ExplorerDeserializerJson())
.registerTypeAdapter(OtherModelClass.class, new OtherModelClassDeserializerJson())
.registerTypeAdapter(OtherModelClass3.class, new OtherModelClass3DeserializerJson())
关于java - 使用 gson 转换器时如何将改造用作单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494591/