I am trying to check internet connection using MVP pattern. For that I have a class MyAppUtil
which takes Context
in its constructor. This is my MVP model class where I am checking internet connection using MyAppUtil.checkConnection(context)
:
public class MainActivityInterectorImpl implements MainActivityContract.IInterector{
Context context;
MainActivityInterectorImpl(Context context) {
this.context = context;
}
@Override
public void getData(OnFinishedListener onFinishedListener) {
boolean result = MyAppUtil.checkConnection(context);
if (result == true) {
onFinishedListener.onSuccess();
} else {
onFinishedListener.onFailure();
}
}
}
Inside VIEW, I'm initializing presenter in the following way :
presenter = new MainActivityPresenterImpl(this, new MainActivityInterectorImpl(this));
As you can see, I am using Context
inside MVP Model. Is this okay in MVP pattern? Any better approach?
Yes, it is bad practice. Make a wrapper of connection checker or similar thing and then pass it to model or presenter.
it should look something like this :
class ConnectionChecker(private val context: Context) {
val isOnline: Boolean
get() {
return try {
val connectivityManager = context.getSystemService(
Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.activeNetworkInfo != null &&
connectivityManager.activeNetworkInfo.isConnected
} catch (exception: Exception) {
false
}
}
}