Search code examples
androiddesign-patternskotlinmvp

How to extend all views with my BasePresenter


Im working on a project and doing mvp on it, now, I have a BaseActivity for all my Activities and a BasePresenter that works with the view of the Activity I'm in, this is done to attach, ditach and know wherever my view is null or not while working with my presenter.

Now, this is working fine for my first view with this

abstract class BasePresenter<T : LoginContract.View> : Presenter<T> {

    private var mMvpView: T? = null

    val isViewAttached: Boolean
        get() = mMvpView != null

    override fun attachView(view: T) {
        mMvpView = view
    }

    override fun detachView() {
        mMvpView = null
    }
}

And in my presenter , I'm calling it like this

class LoginPresenter: BasePresenter<LoginContract.View>(), LoginContract.Presenter {

....

But now , I'm creating a new presenter that is called RegisterPresenter and when I use BasePresenter<> to extend my class with the presenter, it asks to put LoginContract.View in there.

I know that because is coded this way here

abstract class BasePresenter<T : LoginContract.View> : Presenter<T> {
...

But I wonder if there is an approach where I can extend multiple views like this

abstract class BasePresenter<T : multipleViews> : Presenter<T> {

Solution

  • You can't extend multiple classes. You should use some base interface instead.

    How you can do this

    1. Base presenter can use some BaseView interface:
    abstract class BasePresenter<T : BaseView> : Presenter<T>
    

    LoginContract.View interface should extend BaseView. RegisterContract.View also should extend BaseView.

    1. Then if you need one general presenter that works with all views you need to create general interface:
    interface AllViews: LoginContract.View, RegisterContract.View
    
    1. Now you can use it in GeneralPresenter
    class GeneralPresenter : BasePresenter<AllView>