android livedata封装,LiveData+retrofit封装(Java版本)附源码

retrofit网络封装

对android开发来说,常用Volley、okhttp、retofit等网络框架接受服务端信息,其中,由以refrotit最为火热,通常有3种方法对其进行使用:

1.常规retrofit使用如下:

call.enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

response.body().show();

}

@Override

public void onFailure(Call call, Throwable t) {

System.out.println("连接失败");

}

});

}

2.RxJava+retofit封装后就形成简洁的链式调用:

RetrofitFactory.getInstence().API()

.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribe(new Observer>() {

@Override

public void onSubscribe(Disposable d) {

}

@Override

public void onNext(BaseEntity aBeanBaseEntity) {

}

@Override

public void onError(Throwable e) {

}

@Override

public void onComplete() {

}

});

3.LiveData+retrofit进行二次封装,由于google大力推行kotlin,所以封装以kotlin版本居多,但是我kotlin不熟啊😂,要是在项目中大量使用kotlin,怕不是得删库跑路。

6a99a0e0beb1fbebb75263f7e711389e.gif

所以机智如我,根据kotlin改编了一下,效果如下:

3c6d3bf5ff1da809bc447a70331eab0c.png

mainViewModel.getJokeLiveData().observe(this, new Observer() {

@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双向绑定。

定义接收格式,如下:

f444a1ae77ac8d661b1a787235ccef12.png

2.定义服务器地址以及RetrofitManager

6c7ab736245c7faa700f3240aa4aaf06.png

3.封装LiveDataCallAdapter

public class LiveDataCallAdapter implements CallAdapter> {

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 adapt(final Call call) {

return new MyLiveData<>(call, isApiResponse);

}

private static class MyLiveData extends LiveData {

private AtomicBoolean start = new AtomicBoolean(false);

private final Call call;

private boolean isApiResponse;

MyLiveData(Call call, boolean isApiResponse) {

this.call = call;

this.isApiResponse = isApiResponse;

}

@Override

protected void onActive() {

super.onActive();

if (start.compareAndSet(false, true)) {

call.enqueue(new Callback() {

@Override

public void onResponse(@Nullable Call call, @Nullable Response response) {

T body = response.body();

postValue(body);

}

@Override

public void onFailure(@Nullable Call 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值