lifecycleScope 和 SharedFlow 的组合是否消除了对 ViewModel 的需求?

Does a combination of lifecycleScope and SharedFlow eliminate the need for ViewModels?

我是第一次深入 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 交互的第 3 方库。

将整个讨论放在 LiveDataSharedFlowStateFlow 之外。按照您的要求进入 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.

的持有者

即使你想在 LiveData 上使用 SharedFlowStateFlow 我建议你仍然使用 ViewModel 并在其中使用 viewModelScope 而不是仍然执行 UI 和数据之间通常和需要的关注点分离。

ViewModel 在配置更改后仍然存在。活动和片段没有。这是 ViewModel 的主要目的。 ViewModel 不会 自动取消对其 LiveData 的订阅。 LiveData 独立地为自己做这件事。因此,SharedFlow 的存在对 ViewModel 的实用性没有任何影响。

如果您遵循 MVVM 模式并使用 ViewModel 作为 VM,那么使用 SharedFlow 而不是 LiveData 会使它更接近与平台无关并且更容易进行单元测试。