android如何处理错误,android-如何使用LiveData处理错误状态?

博客介绍了在Android中通过扩展MutableLiveData创建持有人模型包装数据的方法。定义了StateData类来管理数据状态,包括创建、成功、错误、加载和完成状态。还给出了扩展的StateLiveData对象及使用示例,以及如何观察数据状态并处理不同情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

您可以从MutableLiveData扩展并创建一个持有人模型来包装您的数据。

这是你的包装模型

public class StateData {

@NonNull

private DataStatus status;

@Nullable

private T data;

@Nullable

private Throwable error;

public StateData() {

this.status = DataStatus.CREATED;

this.data = null;

this.error = null;

}

public StateData loading() {

this.status = DataStatus.LOADING;

this.data = null;

this.error = null;

return this;

}

public StateData success(@NonNull T data) {

this.status = DataStatus.SUCCESS;

this.data = data;

this.error = null;

return this;

}

public StateData error(@NonNull Throwable error) {

this.status = DataStatus.ERROR;

this.data = null;

this.error = error;

return this;

}

public StateData complete() {

this.status = DataStatus.COMPLETE;

return this;

}

@NonNull

public DataStatus getStatus() {

return status;

}

@Nullable

public T getData() {

return data;

}

@Nullable

public Throwable getError() {

return error;

}

public enum DataStatus {

CREATED,

SUCCESS,

ERROR,

LOADING,

COMPLETE

}

}

这是您扩展的LiveData对象

public class StateLiveData extends MutableLiveData> {

/**

* Use this to put the Data on a LOADING Status

*/

public void postLoading() {

postValue(new StateData().loading());

}

/**

* Use this to put the Data on a ERROR DataStatus

* @param throwable the error to be handled

*/

public void postError(Throwable throwable) {

postValue(new StateData().error(throwable));

}

/**

* Use this to put the Data on a SUCCESS DataStatus

* @param data

*/

public void postSuccess(T data) {

postValue(new StateData().success(data));

}

/**

* Use this to put the Data on a COMPLETE DataStatus

*/

public void postComplete() {

postValue(new StateData().complete());

}

}

这就是你的使用方式

StateLiveData> bookListLiveData;

bookListLiveData.postLoading();

bookListLiveData.postSuccess(books);

bookListLiveData.postError(e);

以及如何观察它:

private void observeBooks() {

viewModel.getBookList().observe(this, this::handleBooks);

}

private void handleBooks(@NonNull StateData> books) {

switch (stepIds.getStatus()) {

case SUCCESS:

List bookList = books.getData();

//TODO: Do something with your book data

break;

case ERROR:

Throwable e = books.getError();

//TODO: Do something with your error

break;

case LOADING:

//TODO: Do Loading stuff

break;

case COMPLETE:

//TODO: Do complete stuff if necessary

break;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值