我应该在哪里使用单例,我应该在哪里为 1 个活动应用程序使用视图模型? [英] Where should I be using a singleton and where should I be using a viewmodel for a 1 activity app?

查看:41
本文介绍了我应该在哪里使用单例,我应该在哪里为 1 个活动应用程序使用视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 android 中开发一个单一的活动应用程序,我对是使用视图模型还是使用单例感到矛盾.当涉及到单一活动应用程序时,它们似乎执行基本相同的功能.是否有变量更适合存储在单例和视图模型中,反之亦然?

I'm working on a single activity app in android and I'm conflicted on whether to use a viewmodel or a singleton. They seem to perform essentially the the same functions when it comes to single activity apps. Are there variables that are better to be stored in a singleton vs a viewmodel and vice versa?

推荐答案

我假设您在谈论 ViewModel 类.

I am assuming you are talking about ViewModel class.

ViewModel :您实际上想要多个实例(因为每个实例都会有所不同),而不是为应用程序运行而存在的单个实例.ViewModel 不应有很长的生命周期(您不想要单例的另一个原因).单例对您的整个过程来说是独一无二的.ViewModel 对于单个 Activity 类是唯一的(并且,如果您启动该类的多个 Activity,它对于每个启动的 Activity 都是唯一的)s.ViewModel 的主要用于 MVVM 以及实时数据,并且实现起来很复杂.

ViewModel : You actually WANT multiple instances (since each is going to vary) rather than a single instance that lives for the run of the application. ViewModels should not have a very long lifetime (another reason you don't want a singleton). A singleton is unique for your entire process. A ViewModel is unique for a single Activity class (and, if you start multiple activities of that class, it is unique for each started activity)s.ViewModel's is mainly used for MVVM along with live data and implementing it is complex.

只要您的应用程序的上下文有效,Singleton 就会在内存中.单例对您的整个流程来说是独一无二的.

Singleton will be in memory as long as your application's context is valid. A singleton is unique for your entire process.

既然在这里你知道你总是有一个活动,你可以使用单例,因为它的实现很简单,但对于多活动应用程序

Since, here in you know that you will always be having one activity, you can use singleton as its implementation is easy but for multiple activity application

这篇关于我应该在哪里使用单例,我应该在哪里为 1 个活动应用程序使用视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆