https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

Nat Strangerweather

02/13/2021, 4:25 PM
Hi, I'm a bit confused as I have been using an
AndroidViewModel
so I could pass a context with no memory leak, after this conversation: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1609278349460800?thread_ts=1609277107.460700&cid=C0B8MA7FA The problem since I've recently updated Kotlin is that this line is highlighted with a leak warning:
Copy code
private val context = getApplication<Application>().applicationContext
Why this change and what's the point of
AndroidViewModel
in that case? Any ideas what I could do to avoid the problem?
i

Ian Lake

02/13/2021, 4:27 PM
An
Application
class is a
Context,
you don't need that variable at all
Just make your constructor
val application: Application
if you need to reference a Context variable sometime after init
n

Nat Strangerweather

02/13/2021, 4:29 PM
I see, brilliant, many thanks!
l

Lefko

02/14/2021, 7:20 AM
@Nat Strangerweather no need to change your constructor... just use AndroidViewModel.getApplication()
👍 1