[英]How to send data from thread inside a ViewModel to main Activity/Fragment?
Is there a way to send data from a thread inside a ViewModel to the main Activity/Fragment?有没有办法将数据从 ViewModel 内的线程发送到主 Activity/Fragment?
I'm building an app for financial chart and I'm taking data from an API, so in order to do that I need to put the API call in a thread.我正在为财务图表构建一个应用程序,并且我正在从 API 获取数据,所以为了做到这一点,我需要将 API 调用放在一个线程中。 Apart from that I do some more calculations in order to represent the chart so I figured using a ViewModel.除此之外,我还进行了一些计算以表示图表,因此我想使用 ViewModel。
You can update such LiveData
( MutableLiveData
or MediatorLiveData
) values from a sub-thread by postValue
method rather than setValue
method.您可以通过postValue
方法而不是setValue
方法从子线程更新此类LiveData
( MutableLiveData
或MediatorLiveData
)值。
And from Activity/Fragment, you can observe the LiveData
of your ViewModel
in general ways.从 Activity/Fragment 中,您可以通过一般方式观察ViewModel
的LiveData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.