简体   繁体   中英

Android - context with MVP

I'm about creating a simple app with MVP implementation, and trying to make a permission request in a presenter. To make a permission request, I need to pass Context like this.

        // Location permission has not been granted yet, request it.
        ActivityCompat.requestPermissions(fragmentActivity, new String[]{permission}, requestId);

I've read several articles and they mention that using Context in a presenter is not a good exercise. So, I'm just wondering how people are handling a permission request with MVP. And I don't really know why using Context in a presenter is not good practice. Please, help me to understand how I should handle a permission request and why using context is not good practice.

Thanks

You must never send any object related to Android to the presenter layer, and they must be fully decoupled.

to do these things I always remember a good sentence and that goes Do not inject objects, inject operations and behavior .

it so simple dont inject your context into your presenter which is a wrong practice. instead in your view contract (view interface) add a function called getPermission() then in your view implement that method along with other methods of your contract, then call that method whenever you need the permission.

thats the best way. trust me ;)

There are multiple flavors of MVP out there in practice. I am not here to start a debate which one is right and which one is wrong. As long as a particular flavor works for your scenario, it shall be used.

Instead, I will try to explain why the context in Presenter should be avoided and one of the ways I have avoided in my code.

One of the major reason you should not have a context in the presenter, there might be references to presenter which could leak the activity. In places where I had to deal with a context within the activity, I have accessed through Views.

interface View {
   Context getContext();
}

interface Presenter {
   void setView(View view);
}

So PresenterImpl implements a view, onCreate of the activity and resets it onDestroy of the activity. So the presenter never directly holds the context. But it holds the view, which has knowledge about the View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM