-
Notifications
You must be signed in to change notification settings - Fork 842
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using WeakReference in MvpBasePresenter is flawed #233
Comments
Thanks for reporting! Indeed, that is true, unlikely but in theory this could happen! The proper way is: V view = getView();
if (view !=null){
view.showHello(...);
} We could add a shorthand like this to ifViewAttached(view -> view.showHello(...)); which internally uses What do you think? |
I understand that it is very unlikely considering all conditions that should be met. But still it is a piece of code that feels uncomfortable c: I guess deprecating
It seems to be a common practice among various programmers.
Personally, I just don't see the point in this WeakReference-bulletproofing of someone else's bad code. But that's a whole another "ideal world" discussion. |
3.1.0 deprecates |
Wouldn't deprecating if (getView() != null) {
getView().doThis();
getView().doThat();
} The lint-check in Android Studio will show a warning that EDIT: Ok, I just checked it and it seems like Android Studio will not show any warnings inside a block after |
Yes but with a more concise API (especially in kotlin) like ifViewAttached { view ->
view.doThis()
view.doThat()
} we can avoid pain like NPE. Hence I think the deprecation of |
In Kotlin, can if checks be avoided and safe call operator be used instead? |
yes but still this could happen (theoretically): view?.toThis() // this is executed
// gc runs and view == null
view?.toThat() // this is not executed because view == null because of gc 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 onceViewAttached { view ->
view.doThis()
view.doThat()
} |
Hi,
Using
WeakReference
insideMvpBasePresenter
may potentially lead to NullPointerException in the code like this (taken from the sample code on your site):There is no guarantee that GarbageCollector will not remove object from memory between two subsequent calls to
WeakReference.get()
. This way even whenisViewAttached()
returnstrue
,getView()
may returnnull
. The correct and only way to use WeakReference in this case would be to callWeakReference.get()
only once and assign the result to strong reference.The text was updated successfully, but these errors were encountered: