ihorvitruk / buddysearch

Android Clean Architecture example using MVP, Rx: RxJava, RxAndroid, Dagger 2, Data Binding, Retrolambda, Firebase Database, Firebase Auth, Firebase Messaging (FCM), Realm
Apache License 2.0
208 stars 45 forks source link

onCreateLoader() in BaseActivity memory leak #11

Open IonutNegru87 opened 6 years ago

IonutNegru87 commented 6 years ago

First of all I want to thank you for this demo showing how to implement Clean Architecture using MVP in combination with Dagger2 and other useful tools.

I have noticed that the following issue with the current implementation: The presenter object creation in BaseActivity#onCreateLoader() could create memory leaks.

IonutNegru87 commented 6 years ago

One solution that I've come up with is to use an inner static class for the Loader:

 @Override
    public Loader<PRESENTER> onCreateLoader(int id, Bundle args) {
        return new InnerPresenterLoader<>(this);
    }

    private static class InnerPresenterLoader<V extends View, P extends BasePresenter, B extends
        ViewDataBinding> extends PresenterLoader<P> {

        private final WeakReference<BaseActivity<V, P, B>> activity;

        InnerPresenterLoader(BaseActivity<V, P, B> baseActivity) {
            super(baseActivity);
            this.activity = new WeakReference<>(baseActivity);
        }

        @NonNull
        @Override
        protected P initPresenter() {
            return activity.get().initPresenter().get();
        }
    }

But this doesn't take into consideration when there is no reference to the activity anymore. I'm thinking that some kind of life-cycle should be added to this flow. If I came up with a safe generic approach I will post it here.

Best regards.