對android開發來說,常用Volley、okhttp、retofit等網路框架接受伺服器端資訊,其中,由以refrotit最為火熱,通常有3種方法對其進行使用:
1.常規retrofit使用如下:
call.enqueue(new Callback<Translation>() {
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
response.body().show();
}
@Override
public void onFailure(Call<Translation> call, Throwable t) {
System.out.println("連線失敗");
}
});
}
2.RxJava+retofit封裝後就形成簡潔的鏈式呼叫:
RetrofitFactory.getInstence().API()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseEntity<ABean>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(BaseEntity<ABean> aBeanBaseEntity) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
3.LiveData+retrofit進行二次封裝,由於google大力推行kotlin,所以封裝以kotlin版本居多,但是我kotlin不熟啊😂,要是在專案中大量使用kotlin,怕不是得刪庫跑路。
所以機智如我,根據kotlin改編了一下,效果如下:
mainViewModel.getJokeLiveData().observe(this, new Observer<GetJoke>() {
@Override
public void onChanged(GetJoke getJoke) {
if (getJoke != null) {
activityMainBinding.setJoke(getJoke.getResult().get(0));
}
}
});
4.LiveData 是一種可觀察的資料記憶體類。與常規的可觀察類不同,LiveData 具有生命週期感知能力。這種感知能力可確保 LiveData 僅更新處於活躍生命週期狀態的應用元件觀察者, 當 Activity 和 Fragment 的生命週期被銷燬時,系統會立即退訂它們。與RxJava相比,具有門檻低,防止記憶體漏失的優點。
下面開始正題,demo在末尾,可直接下載,下篇會加入LiveData和ObservableField雙向繫結。
2.定義伺服器地址以及RetrofitManager
3.封裝LiveDataCallAdapter
public class LiveDataCallAdapter<T> implements CallAdapter<T, LiveData<T>> {
private Type responseType;
private boolean isApiResponse;
LiveDataCallAdapter(Type responseType, boolean isApiResponse) {
this.responseType = responseType;
this.isApiResponse = isApiResponse;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public LiveData<T> adapt(final Call<T> call) {
return new MyLiveData<>(call, isApiResponse);
}
private static class MyLiveData<T> extends LiveData<T> {
private AtomicBoolean start = new AtomicBoolean(false);
private final Call<T> call;
private boolean isApiResponse;
MyLiveData(Call<T> call, boolean isApiResponse) {
this.call = call;
this.isApiResponse = isApiResponse;
}
@Override
protected void onActive() {
super.onActive();
if (start.compareAndSet(false, true)) {
call.enqueue(new Callback<T>() {
@Override
public void onResponse(@Nullable Call<T> call, @Nullable Response<T> response) {
T body = response.body();
postValue(body);
}
@Override
public void onFailure(@Nullable Call<T> call, @Nullable Throwable t) {
if (isApiResponse) {
postValue((T) new ApiResponse<>(ApiResponse.CODE_ERROR, t.getMessage()));
} else {
postValue(null);
}
}
});
}
}
}
}
4.封裝LiveDataCallAdapterFactory
public class LiveDataCallAdapterFactory extends CallAdapter.Factory {
@Nullable
@Override
public CallAdapter<?, ?> get(@Nullable Type returnType, @Nullable Annotation[] annotations, @Nullable Retrofit retrofit) {
if (getRawType(returnType) != LiveData.class) {
return null;
}
Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
Type rawType = getRawType(observableType);
boolean isApiResponse = true;
if (rawType != ApiResponse.class) {
isApiResponse = false;
}
if (observableType instanceof ParameterizedType) {
throw new IllegalArgumentException("resource must be parameterized");
}
return new LiveDataCallAdapter<>(observableType, isApiResponse);
}
}
5.定義Api介面以及伺服器地址
參考文章:LiveData+Retrofit網路請求實戰
github地址: https://github.com/zcyyouminghuo/mvvmRetrofit
CSDN資源: https://download.csdn.net/download/qq_42625299/13011094