buddysearch icon indicating copy to clipboard operation
buddysearch copied to clipboard

onCreateLoader() in BaseActivity memory leak

Open IonutNegru87 opened this issue 7 years ago • 1 comments

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 avatar Nov 13 '17 10:11 IonutNegru87

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.

IonutNegru87 avatar Nov 13 '17 11:11 IonutNegru87