问题描述
对于 LiveData
,是否有与RxJava的Observable中的 blockingNext
或 blockingSingle
类似的东西来同步获取值?如果没有,我如何实现相同的行为?
For LiveData
, is there something similar to blockingNext
or blockingSingle
in RxJava's Observable to get the value synchronously? if not, how can i achieve the same behavior?
推荐答案
您可以调用 getValue()
返回当前值(如果有).但是,没有阻塞直到有值"选项.通常,这是因为 LiveData
是要在主应用程序线程上使用的,因此应避免无限阻塞调用.
You can call getValue()
to return the current value, if there is one. However, there is no "block until there is a value" option. Mostly, that is because LiveData
is meant to be consumed on the main application thread, where indefinitely-blocking calls are to be avoided.
如果您需要阻塞直到有一个值",请使用RxJava并确保您在后台线程上进行观察.
If you need "block until there is a value", use RxJava and ensure that you are observing on a background thread.
这篇关于如何同步从LiveData获得价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!