[英]Kotlin: Coroutine with Live Data or only Coroutines?
which is better between these two 这两者之间哪个更好
1) Using coroutines in Viewmodel to fetch data from network and updating View using live data? 1)在Viewmodel中使用协同程序从网络获取数据并使用实时数据更新View?
2) Using coroutine from View to call suspend function in viewmodel that fetches data from network? 2)使用View中的coroutine来调用viewmodel中的suspend函数,该函数从网络中获取数据?
Another question 另一个问题
Should we be using livedata for use cases where we need to update UI only once from backend, like data won't be changing while user is on that screen 我们是否应该将livingata用于需要从后端仅更新一次UI的用例,就像用户在该屏幕上时数据不会改变一样
I'm voting for (1), using LiveData
for that final step of moving the data from the ViewModel
to the View. 我投票给(1),使用
LiveData
进行将数据从ViewModel
移动到View的最后一步。
Here's why: if you start a coroutine in the UI which fetches the data through your ViewModel
... 原因如下:如果您在UI中启动协程,通过
ViewModel
获取数据...
getData()
in the View. getData()
这样的暂停调用。 Whether that's a Fragment
or an Activity
, that coroutine will deliver the result to only that specific instance. Fragment
还是Activity
,该协程将仅将结果传递给该特定实例。 If it gets recreated due to a configuration change, you'll need to fetch again in the new instance. ViewModel
and around the network will be lost (eg any progress on a long running network call), since your coroutine is cancelled when your View is destroyed. ViewModel
和网络周围完成的任何工作都将丢失(例如,长时间运行的网络呼叫的任何进展) ),因为当你的视图被销毁时你的协程被取消了。 In comparison, if you start coroutines in your ViewModel
and then place the result in a LiveData
: 相比之下,如果您在
ViewModel
启动协同程序,然后将结果放在LiveData
:
onCleared
) instead of at configuration changes. onCleared
)而不是在配置更改时取消协同程序。 LiveData
observers will only be called when the View exists and is in an active (foreground) state, so you don't have to worry about getting results when your View isn't ready for it (or doesn't exist anymore). LiveData
观察者只有在View存在且处于活动(前景)状态时才会被调用,因此当View未准备好(或不再存在)时,您不必担心获得结果。 LiveData
and receive the value that's already loaded. LiveData
并接收已加载的值。 Or, if your data is still loading, it will even eventually receive the result of the network call that was started for a previous View instance.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.