Using WeakReference in MvpBasePresenter is flawed
See original GitHub issueHi,
Using WeakReference
inside MvpBasePresenter
may potentially lead to NullPointerException in the code like this (taken from the sample code on your site):
if (isViewAttached())
getView().showHello(greetingText);
There is no guarantee that GarbageCollector will not remove object from memory between two subsequent calls to WeakReference.get()
. This way even when isViewAttached()
returns true
, getView()
may return null
. The correct and only way to use WeakReference in this case would be to call WeakReference.get()
only once and assign the result to strong reference.
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (5 by maintainers)
Top Results From Across the Web
You don't have to use WeakReference to avoid memory leaks
I personally think that, not only that is a wrong argument but it is also totally misleading. WeakReference should be the last resort...
Read more >Android MVP, Retrofit & Rx - AppFoundry
While there is nothing wrong with using the Retrofit synchronous api on ... has a @Nullable annotation (uses a weak reference on the...
Read more >A rare usage of WeakReference? - Stack Overflow
Still nothing seems wrong (I believe) and I don't like the instance persisted with the class and that's why I'm trying to do...
Read more >Weak References in Java - Baeldung
First off, the Garbage Collector clears a weak reference, so the referent is no longer accessible. Then the reference is placed in a ......
Read more >Understanding Weak Reference In JavaScript
It has errors (dog variable and names in .forEach), no explanation of WeakRef, and bad indentation in examples. I do not see much...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Thanks for reporting! Indeed, that is true, unlikely but in theory this could happen! Actually I wanted to deprecate
isViewAttached()
in3.0
.The proper way is:
We could add a shorthand like this to
MvpBasePresenter
:which internally uses
View view = getView(); if (view != null) { ... }
as shown in the first code snippet.What do you think?
yes but still this could happen (theoretically):
whereas with ifViewAttached() its a do all in the lambda because view is guaranteed not to be null or don’t execute the lambda at all. Also we have to take java users into account.
Also this API seems to me more consistent to what
MvpQueuingBasePresenter
offers: