Advertisement
seroperson

model

Oct 14th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. public class InfoModelImpl implements InfoModel {
  2.  
  3.   @NonNull
  4.   private final GithubService restApi;
  5.   @NonNull
  6.   private final String user;
  7.   @NonNull
  8.   private final RealmConfiguration configuration;
  9.   @NonNull
  10.   private final Scheduler scheduler;
  11.   @Nullable
  12.   private Realm realm;
  13.  
  14.   public InfoModelImpl(@NonNull String user,
  15.                        @NonNull RealmConfiguration configuration,
  16.                        @NonNull Scheduler scheduler,
  17.                        @NonNull GithubService restApi) {
  18.     this.user = user;
  19.     this.configuration = configuration;
  20.     this.scheduler = scheduler;
  21.     this.restApi = restApi;
  22.   }
  23.  
  24.   @AnyThread
  25.   @NonNull
  26.   @Override
  27.   public Observable<GithubUser> updateInfo() {
  28.     return restApi.getUser(user).observeOn(scheduler)
  29.                   .doOnNext(user -> {
  30.                     if (realm == null || realm.isClosed()) {
  31.                       throw new IllegalStateException("You should subscribe on #observeInfo() first");
  32.                     }
  33.                     realm.executeTransaction(r -> {
  34.                       GithubUser realmObject = realm.where(GithubUser.class).findFirst();
  35.                       if (realmObject == null) {
  36.                         realm.copyToRealmOrUpdate(user);
  37.                       } else {
  38.                         realmObject.setAvatarUrl(user.getAvatarUrl());
  39.                         realmObject.setName(user.getName());
  40.                       }
  41.                     });
  42.                   });
  43.   }
  44.  
  45.   @AnyThread
  46.   @NonNull
  47.   @Override
  48.   public Observable<GithubUser> observeInfo() {
  49.     return Observable.defer(() -> {
  50.       if (realm != null && !realm.isClosed()) {
  51.         throw new IllegalStateException("You can't subscribe #observeInfo() twice");
  52.       }
  53.       realm = Realm.getInstance(configuration);
  54.       return realm.where(GithubUser.class).findFirstAsync()
  55.                      .<GithubUser>asObservable()
  56.                      .filter(p -> p.isLoaded() && p.isValid())
  57.                      .doOnUnsubscribe(() -> {
  58.                        realm.close();
  59.                        realm = null;
  60.                      })
  61.                      .distinctUntilChanged();
  62.     }).subscribeOn(scheduler);
  63.   }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement