如何使用 LiveData 处理错误状态? [英] How to handle error states with LiveData?

查看:25
本文介绍了如何使用 LiveData 处理错误状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的 LiveData 可以是在某些场景中用作替代 RxJava 的 observables.但是,与 Observable 不同的是,LiveData 没有错误回调.

The new LiveData can be used as a replacement for RxJava's observables in some scenarios. However, unlike Observable, LiveData has no callback for errors.

我的问题是:我应该如何处理 LiveData 中的错误,例如当它由某些由于 IOException 而无法检索的网络资源支持时?

My question is: How should I handle errors in LiveData, e.g. when it's backed by some network resource that can fail to be retrieved due to an IOException?

推荐答案

在 Google 的其中一个 Android 架构组件示例应用,它们将 LiveData 发出的对象包装在一个类中,该类可以包含所发出对象的状态、数据和消息.

In one of Google's sample apps for Android Architecture Components they wrap the LiveData emitted object in a class that can contain a status, data, and message for the emitted object.

https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/vo/Resource.kt

通过这种方法,您可以使用状态来确定是否有错误.

With this approach you can use the status to determine if there was an error.

这篇关于如何使用 LiveData 处理错误状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆