Search code examples
androidkotlinandroid-mvp

android MVP pattern on memory leak


Currently i am using MVP pattern on android with Contract. So in example my interactor is like this:

interface MainInteractor {
    interface Activity {
        //function here
    }

    interface Presenter {
        //function here
    }
}

and my Presenter class contains something like this

class MainPresenter(
    var activity : MainInteractor.Activity
) : MainInteractor.Presenter {

    //interface function that calls API (async)
    fun callNetwork() {
        //code here 
    }
}

In sense i want to know if this kind of pattern will cause memory leak if calling network hasn't finished but the activity has already been destroyed. I know for AsyncTask, weak reference will be used to avoid memory leak. Is it the same case here? And if it does cause memory leak are there any way to fix it aside from weak reference.


Solution

  • You could make method attach and detach. In attach you could initialize something, in detach you could finilize something. For example you could set null to your activity contract interface variable and inside all your callbacks before call method check if not null.

    Case with AsyncTask is not similar to your case. With AsyncTask we passed inside View or Activity link, it means after rotate previous activity/view destroyed, but out async task has old link and GC cannot clear memory.