【发布时间】: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