Office Hours — Today, October 1

Monday, September 28

Mark M.
has entered the room
Mark M.
turned on guest access
Oct 1
8:05 PM
PPartisan
has entered the room
Mark M.
hello, PPartisan!
how can I help you today?
PPartisan
Hello Mark :)
I had a question about the correct use of WeakReference in AsyncTasks
Mark M.
OK... what is your question?
PPartisan
I've seen two examples of how it's used. In one instance, `weakreference.get()` itself is passed as the argument. In the other, a `Context` of some type is passed, as a WeakReference variable is instantiated inside the constructor
and**
Is there a difference between the two?
Mark M.
"`weakreference.get()` itself is passed as the argument" -- passed as the argument to... what?
8:10 PM
PPartisan
To an AsyncTask's constructor where, for example, it will be stored in a variable and used to access Strings etc.
Mark M.
the difference is that they are completely unrelated, then
what matters is who holds the WeakReference
the result of get() is the underlying object, not the WeakReference itself
if the AsyncTask is holding the WeakReference, we're saying "we'd kinda like to hold onto this object as long as the task is running, but feel free to GC it if you need to"
if something else is holding the WeakReference, and the AsyncTask is holding the actual object, so long as the AsyncTask is outstanding, the actual object cannot be GC'd
PPartisan
So it would make most sense to pass some form of Context (say an Activity) in the AsyncTask's constructor, store it in a WeakReference variable, and use weakreference.get() in onPreExecute or anywhere else when context is required?
Mark M.
I wouldn't do it that way
but I seem to recall seeing others go that route
IMHO, an AsyncTask is only useful if paired with a retained fragment
8:15 PM
Mark M.
and the AsyncTask shouldn't have anything to do with a Context (other than Application) from within doInBackground()
so, for example, if I have an AsyncTask that needs to read an asset, I'll get the AssetManager in the AsyncTask constructor and hold it, rather than hold some Context and get the AssetManager in doInBackground()
though on the whole, I don't use AsyncTask a whole lot anymore outside of book examples
usually, whatever I needed the task for is either handled by a library (image loading) or is something I'm handling separately (e.g., ordinary thread, posting results via an event bus)
8:25 PM
Mark M.
any last questions?
PPartisan
Thanks Mark, no, that's all from me
Mark M.
OK
that's a wrap for today's chat, then
the transcript will be posted to https://commonsware.com/office-hours/ shortly
8:30 PM
Mark M.
the next chat is Saturday at 4pm US Eastern
have a pleasant day!
PPartisan
has left the room
Mark M.
turned off guest access

Monday, September 28

 

Office Hours

People in this transcript

  • Mark Murphy
  • PPartisan