Skip to content

Instantly share code, notes, and snippets.

@hboregio
Last active August 26, 2016 08:59
Show Gist options
  • Save hboregio/de17115130a452b9c2cad55936d004b2 to your computer and use it in GitHub Desktop.
Save hboregio/de17115130a452b9c2cad55936d004b2 to your computer and use it in GitHub Desktop.
// BasePresenter.java (Base class for all our Presenters)
public abstract class BasePresenter<V> {
private WeakReference<V> mView;
public void bindView(@NonNull V view) {
mView = new WeakReference<>(view);
}
public void unbindView() {
mView = null;
}
public V getView() {
if (mView == null) {
return null;
} else {
return mView.get();
}
}
protected final boolean isViewAttached() {
return mView != null && mView.get() != null;
}
}
// IForgotPasswordView.java (view interface)
public interface IForgotPasswordView {
void showLoading();
void hideLoading();
void setEmailText(String email);
void showEmailNotValidError();
void showPasswordRequestOk(String message);
void showPasswordRequestFail();
}
// ForgotPasswordFragment.java (view implementation)
public class ForgotPasswordFragment implements IForgotPasswordView,
View.OnClickListener {
// Triggered by the user clicking a button
public void onResetPasswordClick() {
String email = mEmailEditText.getText().toString();
// Forward all logic to the Presenter
mPresenter.requestPasswordChange(email);
}
}
// ForgotPasswordPresenter.java
public class ForgotPasswordPresenter extends BasePresenter<IForgotPasswordView> {
public void requestPasswordChange(String email) {
if (!Utils.isEmailValid(email)) {
// Make sure the view is still alive before trying to access it
if(isViewAttached()) {
getView().showEmailNotValidError();
}
} else {
requestPasswordChangeAsync(email);
}
}
private void requestPasswordChangeAsync(String email) {
// Update the view's UI elements
if(isViewAttached()) {
getView().hideKeyboard();
getView().showLoading();
// Call our API (results are posted back on an EventBus)
api.forgotPassword(email);
}
}
// Subscription to the event bus
@Subscribe
public void onEvent(final Event event) {
if (isViewAttached()) {
// Update the view's UI elements
getView().hideLoading();
switch (event.getType()) {
case FORGOT_PASSWORD_OK:
getView().showPasswordRequestOk((String) event.getData());
break;
case FORGOT_PASSWORD_FAILED:
getView().showPasswordRequestFail();
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment