Last active
October 19, 2018 01:46
-
-
Save Denis-Avenger/2645b0cfaf22cb70b71de40cff59a4f0 to your computer and use it in GitHub Desktop.
MVP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface MyMvpContract { | |
interface Presenter { | |
void attachView(MyMvpContract.View view); | |
void detachView(); | |
//some other code | |
} | |
interface View { | |
//some other code | |
} | |
//some other code | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyPresenter extends ViewModel implements | |
MyMvpContract.Presenter { | |
private MyMvpContract.View mView; | |
private LiveData<List<Event>> mEvents = new MutableLiveData<>(); | |
public LiveData<List<Event>> getEvents() { | |
return mEvents; | |
} | |
@Override | |
public void attachView(MyMvpContract.View view) { | |
if (mView == null) { | |
mView = view; | |
getEvents().observe((LifecycleOwner) view, events -> { | |
//call View method to update UI | |
}); | |
} | |
// do nothing if fragment was not distroyed but only was hidden | |
} | |
@Override | |
public void detachView() { | |
mView = null; | |
} | |
//Some other code | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyView extends LifecycleFragment implements MyMvpContract.View { | |
private MyMvpContract.Presenter mPresenter; | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, | |
Bundle savedInstanceState) { | |
mPresenter = ViewModelProviders.of(this).get(SimInfoPresenter.class); | |
// some code | |
mPresenter.attachView(this); | |
return v; | |
} | |
@Override | |
public void onDestroy() { | |
mPresenter.detachView(); | |
super.onDestroy(); | |
} | |
//some other code | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment