Advertisement
seroperson

presenter

Oct 14th, 2016
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. public class InfoPresenterImpl extends MvpBasePresenter<InfoView> implements InfoPresenter {
  2.  
  3.   @NonNull
  4.   private final InfoModel model;
  5.   @Nullable
  6.   private Subscription observing;
  7.   @Nullable
  8.   private Subscription updating;
  9.  
  10.   public InfoPresenterImpl(@NonNull InfoModel model) {
  11.     this.model = model;
  12.   }
  13.  
  14.   @Override
  15.   public void attachView(InfoView attached) {
  16.     super.attachView(attached);
  17.     if (!isSubscribed(observing)) {
  18.       observing = model.observeInfo().subscribe(s -> {
  19.         InfoView view = getView();
  20.         if (isViewAttached()) {
  21.           view.setData(s);
  22.           view.showContent();
  23.         }
  24.       }, t -> {
  25.           if (isViewAttached()) {
  26.             getView().showError(t, false);
  27.           }
  28.         });
  29.     }
  30.   }
  31.  
  32.   @Override
  33.   public void detachView(boolean retainInstance) {
  34.     super.detachView(retainInstance);
  35.     if (!retainInstance) {
  36.       tryToUnsubscribe(observing);
  37.       tryToUnsubscribe(updating);
  38.     }
  39.   }
  40.  
  41.   @Override
  42.   @AnyThread
  43.   public void loadInformation(boolean pullToRefresh) {
  44.     getView().showLoading(pullToRefresh);
  45.     tryToUnsubscribe(updating);
  46.     updating = model.updateInfo().subscribe(ignored -> { }, t -> {
  47.       if (isViewAttached()) {
  48.         getView().showError(t, true);
  49.       }
  50.     });
  51.   }
  52.  
  53.   private void tryToUnsubscribe(@Nullable Subscription subscription) {
  54.     if (isSubscribed(subscription)) {
  55.       subscription.unsubscribe();
  56.     }
  57.   }
  58.  
  59.   private boolean isSubscribed(@Nullable Subscription subscription) {
  60.     return subscription != null && !subscription.isUnsubscribed();
  61.   }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement