Android Jetpack 中的单个 ViewModel 与多个 ViewModel

发布于 2025-01-15 16:48:21 字数 756 浏览 3 评论 0原文

我遇到这种情况:视图从 Android ViewModel 渲染数据,但在功能上它们是不同的。例如,一个可以显示一些财务数据,另一个可以显示与体育相关的数据。

一种方法是(假设这里只有 2 个,但可能更多)

Fragment -> View 1 ->   |                      | Repository for 1
                        |  --> View Model -->  |
            View 2 ->   |                      | Repository for 2
            ...

另一种是

Fragment -> View 1 ->   |  --> View Model 1 --> | Repository for 1
                        
            View 2 ->   |  --> View Model 2 --> | Repository for 2
            ...

我更喜欢第二种,因为至少我们将拥有单独的 viewModelScopes(基于 ViewModel 内部使用的标签)。作为为一个视图启动的主管作业协程不会影响(在出现错误的情况下)为其他视图启动的协程,但我们仍然会有清晰的代码组织。

选择第一种方法(有一个 Android ViewModel)有什么争议吗?

I have this situation where view renders data from Android ViewModel(s) but functionally they are distinct. One could be showing, say, some financial data and the other one sports-related.

One approach would be (assuming only 2 here but could be lot more)

Fragment -> View 1 ->   |                      | Repository for 1
                        |  --> View Model -->  |
            View 2 ->   |                      | Repository for 2
            ...

Other one being

Fragment -> View 1 ->   |  --> View Model 1 --> | Repository for 1
                        
            View 2 ->   |  --> View Model 2 --> | Repository for 2
            ...

I prefer the second one because, at least, we will have individual viewModelScopes (based on the tag used internally by ViewModel). Being supervisor jobs coroutines launched for one view will not impact (in case of errors) ones launched for others but still, we will have clear code organization.

Is there any argument to chose the first approach (having a single Android ViewModel)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文