Android MVP: safe use Context in Presenter

前端 未结 4 691
悲&欢浪女
悲&欢浪女 2021-01-17 10:02

In my app I work with ContentProvider and use LoaderManager.LoaderCallbacks.

Fragment (View)



        
4条回答
  •  离开以前
    2021-01-17 10:23

    public class ArticleCatalogPresenter extends BasePresenter
            implements LoaderManager.LoaderCallbacks {
    
        View view;             
        ...
        private Loader onCreateArticleCatalogLoader(Bundle args) {    
                int categoryId = args.getInt(CATEGORY_ID);
                Loader loader = new ArticleCatalogLoader(context, categoryId); // need Context
                return loader;
        }
    }
    

    So you want the context in your Presenter to build a new instance of ArticleCatalogLoader. Right?

    If so, pass the instance to the Presenter through constructor. So in your Activity or DI container when you want to build the Presenter object, do something like:

    ArticleCatalogPresenter articleCatalogPresenter=new ArticleCatalogPresenter(articleCatalogView,new ArticleCatalogLoader(context,categoryId));
    

    This way your Presenter will not be dependent on context and will be fully testable.

    About your concern on memory leak, you can easily avoid that by listening to onStop() in your View and then call the corresponding method in your Presenter to cancel any network request or context dependent task.

    I have written an MVP library which helps a lot with saving the amount of boilerplate needed for MVP a well as preventing memory leaks.

提交回复
热议问题