英文:
Is passing activity context to a function without storing it safe?
问题
我知道存储活动上下文,例如将其传递给ViewModel的构造函数,是不良做法。
但是,如果我在ViewModel或其他非生命周期感知的类中有一个接受上下文作为参数的函数,而不将其存储在类级别,是否会消除内存泄漏的潜力?
英文:
I know storing activity context, for example passing it in a constructor to a ViewModel, is bad practice.
However, if I have a function in my ViewModel or other non lifecycle-aware class that takes context as a parameter without storing it at the class level, does this remove the potential for memory leaks?
答案1
得分: 2
要回答这个问题,是的!如果您没有将context
存储在类级别,并且不在后台任务中使用context
,则将context
作为参数传递不会有潜在的泄漏问题。函数参数的生命周期很短,在执行完成后不会保留任何引用。
但是,将context
传递给ViewModel
会引发其他问题,最好始终避免在构造函数/方法中或在ViewModel
内部的任何形式中使用Android组件,以将其与Android框架依赖解耦,从而有助于在独立的Java环境中进行单元测试!
英文:
To answer the question, Yes! Having context
as parameter does not have any potential leak if you are not storing it in class level given you don't use the context
in some background task. The function parameters are short lived and would not hold any references after execution is complete.
But, passing context
to ViewModel
has other problems, it is always better to avoid using android components either in constructor/methods or in any form inside Viewmodel
to decouple it from android framework dependency and hence helps in unit testing in isolated java environment!
答案2
得分: -1
另外,您可以通过以下方式获取在活动中显示的视图:
View v = ((Activity)context).findViewById(R.id.viewId);
这些视图引用也不应该被存储,否则可能会导致内存泄漏。
英文:
Also, you could do things like getting the views that are shown in an activity by doing
View v = ((Activity)context).findViewById(R.id.viewId);
These view references should not be stored either otherwise that can cause leaks too.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论