改造2入队方法运行2次
作者:互联网
我是翻新库的新手.我正在开发一个必须进行多个API调用的应用程序,但是当我尝试进行第一个API调用时,这个问题困扰着我.
我面临的问题是,每当我过去用来调用改造的异步调用方法时,onResponse方法中的功能就会运行2次…
这是我异步调用API调用时的代码…
final ApiModule apiService = ApiServiceGenerator.createService(ApiModule.class);
Call <ConfigResponse> call = apiService.getConfig();
call.enqueue(new Callback<ConfigResponse>() {
@Override
public void onResponse(Call<ConfigResponse> call, Response<ConfigResponse> response) {
try {
if (response.isSuccessful()) {
Log.e("MyTag", "This is running");
}
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ConfigResponse> call, Throwable t) {
e.printStackTrace();
}
});
在设备上运行该应用程序后,当我看到我的android studio记录器时,它就会向我显示日志消息-
E/MyTag: This is running
E/MyTag: This is running
似乎在这里它运行了2次!
我不明白为什么它要运行2次.
这个你能帮我吗…
只是为了获得更多帮助…
我已经实现了这样的代码.
ApiModule接口(在其中定义了我的API调用URL)
public abstract interface ApiModule {
@GET("config")
Call<ConfigResponse> getConfig();
}
ApiServiceGenerator像这样-
public class ApiServiceGenerator {
public static final String API_BASE_URL = "https://www.example.com/";
private static OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("App-Secret", "some-secret-key").build();
return chain.proceed(newRequest);
}
})
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) // Just For logging
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ArrayAdapterFactory())
.create();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create()));
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
public static Retrofit retrofit() { // For Error Handing when non-OK response is received from Server
OkHttpClient httpClient = new OkHttpClient.Builder().build();
OkHttpClient client = httpClient;
return builder.client(client).build();
}
}
解决方法:
终于我解决了我的问题.
这不是翻新库的问题.. !!
其实这是我的坏事.我打开了两次片段(在回答这个问题之前我不知道)…
这就是为什么片段中的代码运行两次的原因,这让我认为改造响应运行了两次…
标签:retrofit2,api,retrofit,asynccallback,android 来源: https://codeday.me/bug/20191118/2031047.html