传递活动上下文给一个函数而不存储它是否安全?

huangapple go评论57阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月8日 04:24:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定