android - LifecycleScope 和 SharedFlow 的组合是否消除了对 ViewModel 的需求?

标签 android kotlin viewmodel kotlin-flow

我是第一次深入 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
    }
}

当生命周期超出范围时,这应该取消。我在这里错过了一个问题吗?或者是否有充分的理由使用 ViewModel?此处假设我不需要与 LiveData 或 ViewModel 之外的第三方库进行交互。

最佳答案

将整个讨论放在 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 和数据之间通常且必需的关注点分离。

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

相关文章:

android - 如何对扩展 AndroidViewModel 的 ViewModel 进行单元测试。构造函数中的应用程序有问题

java - 检查复选框是否被选中返回空指针

Android 推特连接?

android - 当请求不是来自 Firebase 控制台时,RemoteMessage.GetNotification() 返回 null?

android - logcat android studio 中的随机消息

c# - 如何避免列表重复

android - 在 tabhost 上 ScrollView

kotlin - Kotlin中省略的 `Return`需要额外的代码。如何解决?

android - 在 Android Studio 中用 Kotlin 自动生成 getter 和 setter

android - 如果没有@Provides注释的方法,则无法提供Dagger/MissingBinding androidx.lifecycle.ViewModelProvider.Factory