whether objects using weakreference in java singletons can be recycled
retrofit is sufficient to use singletons to put retrofit into weakreference
public class RetrofitSingleton {
private WeakReference<Retrofit> retrofitWeakReference;
private RetrofitSingleton() {
}
private static volatile RetrofitSingleton instance = null;
public static RetrofitSingleton getInstance() {
if (instance == null) {
synchronized (RetrofitSingleton.class) {
if (instance == null) {
instance = new RetrofitSingleton();
}
}
}
return instance;
}
private synchronized Retrofit getRetrofit() {
if (retrofitWeakReference == null) {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new TokenHeadweInterceptor())
.readTimeout(8, TimeUnit.SECONDS)
.writeTimeout(8, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(GsonUtil.buildGosn()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
retrofitWeakReference = new WeakReference<>(retrofit);
}
return retrofitWeakReference.get();
}
}