如何使用LiveData处理错误状态? [英] How to handle error states with LiveData?
问题描述
新的 LiveData
可以替代在某些情况下RxJava的可观察对象.但是,与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.
With this approach you can use the status to determine if there was an error.
这篇关于如何使用LiveData处理错误状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!