gpt4 book ai didi

android - 生命周期范围和 SharedFlow 的组合是否消除了对 ViewModel 的需求?

转载 作者:行者123 更新时间:2023-12-05 00:18:24 26 4
gpt4 key购买 nike

我第一次潜入 Kotlin Flow,我想知道 ViewModel 是否还有一席之地。 ViewModel 的优势在于它具有生命周期感知能力,并且会在 Activity 被销毁时自动取消对 ViewModel 的 LiveData 的订阅。 Kotlin SharedFlow 的工作方式与 LiveData 类似,因为它可以被多个观察者订阅。在 Kotlin 中,lifecycleScope 协程应该在生命周期结束时取消所有子协程。所以如果我们有这样的事情:

lifecycleScope.launch(Dispatchers.IO) {
//Do something
flow.emit(result)
}

lifecycleScope.launch(Dispatchers.Main) {
flow.collect {
//Display the data
}
}
当生命周期超出范围时,这应该取消。我在这里错过了一个问题吗?还是有充分的理由使用 ViewModels?假设这里没有我需要与预期 LiveData 或 ViewModels 交互的第三方库。

最佳答案

将整个讨论搁置一旁 LiveData对比 SharedFlowStateFlow .来到 ViewModels正如你所问。如果我们要通过文件

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.


UI controllers such as activities and fragments are primarily intended to display UI data, react to user actions, or handle operating system communication, such as permission requests. Requiring UI controllers to also be responsible for loading data from a database or network adds bloat to the class. Assigning excessive responsibility to UI controllers can result in a single class that tries to handle all of an app's work by itself, instead of delegating work to other classes. Assigning excessive responsibility to the UI controllers in this way also makes testing a lot harder.


It's easier and more efficient to separate out view data ownership from UI controller logic.


我想这总结得很好。确实 lifeCycleScope可以消除 ViewModel 的需要在某种程度上,但是 ViewModel不仅仅是成为 LiveData 的持有者.
即使你想使用 SharedFlowStateFlow超过 LiveData我建议您仍然使用 ViewModel并在其中使用 viewModelScope而是仍然在 UI 和数据之间执行通常的和必需的关注点分离。

关于android - 生命周期范围和 SharedFlow 的组合是否消除了对 ViewModel 的需求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67955354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com