Skip to content

Instantly share code, notes, and snippets.

@Denis-Avenger
Last active October 19, 2018 01:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Denis-Avenger/2645b0cfaf22cb70b71de40cff59a4f0 to your computer and use it in GitHub Desktop.
Save Denis-Avenger/2645b0cfaf22cb70b71de40cff59a4f0 to your computer and use it in GitHub Desktop.
MVP example
public interface MyMvpContract {
interface Presenter {
void attachView(MyMvpContract.View view);
void detachView();
//some other code
}
interface View {
//some other code
}
//some other code
}
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
}
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