Exemplo n.º 1
0
  public void addFriend(final FriendRequest friendRequest) {
    FriendshipAddForm dataForm = new FriendshipAddForm();
    dataForm.friend_id = friendRequest.getUid();

    friendshipResource
        .save(dataForm)
        .subscribeOn(Schedulers.io())
        .observeOn(Schedulers.io())
        .subscribe(
            response -> {
              // TODO show add friend Tip

              Friend friend = new Friend();
              friend.setUid(friendRequest.getUid());
              friend.setUsername(friendRequest.getUsername());
              friend.setNickname(
                  TextUtils.isEmpty(friendRequest.getNickname())
                      ? friendRequest.getDisplayName()
                      : friendRequest.getNickname());
              friend.setAvatar(friendRequest.getAvatar());
              friendDao.insert(friend);
            },
            error -> {
              // TODO show error info
            });

    // update friendRequest
    friendRequest.setStatus(FriendRequestStatus.ACCEPT.name());
    friendRequestDao.update(friendRequest);
  }
    public RetentionFragment() {
      final Gson gson =
          new GsonBuilder()
              .registerTypeAdapter(Message.class, new Message.Deserializer())
              .registerTypeAdapter(MessageType.class, new MessageType.SerializerDeserializer())
              .create();

      final OkHttpClient okHttpClient = new OkHttpClient();
      final RxWebSockets webSockets =
          new RxWebSockets(
              okHttpClient,
              new Request.Builder()
                  .get()
                  .url("ws://10.10.0.2:8080/ws")
                  .addHeader("Sec-WebSocket-Protocol", "chat")
                  .build());
      final GsonObjectSerializer serializer = new GsonObjectSerializer(gson, Message.class);
      final RxObjectWebSockets jsonWebSockets = new RxObjectWebSockets(webSockets, serializer);
      final SocketConnection socketConnection =
          new SocketConnectionImpl(jsonWebSockets, Schedulers.io());
      presenter =
          new MainPresenter(
              new Socket(socketConnection, Schedulers.io()),
              Schedulers.io(),
              AndroidSchedulers.mainThread());
    }
Exemplo n.º 3
0
 private void doLogin(final String username, String password) {
   subscription.add(
       api.getUserInfo(username)
           .observeOn(Schedulers.io())
           .subscribeOn(Schedulers.io())
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(
               new Action1<Result<User>>() {
                 @Override
                 public void call(Result<User> t) {
                   showProgress(false);
                   if (t.getStatus() == 200) {
                     Toast.makeText(getApplicationContext(), t.getMsg(), Toast.LENGTH_SHORT)
                         .show();
                     String sid = t.getData().getUname();
                   }
                 }
               },
               new Action1<Throwable>() {
                 @Override
                 public void call(Throwable throwable) {
                   GlobalUtils.showToastShort(LoginActivity.this, getString(R.string.net_error));
                   showProgress(false);
                 }
               }));
 }
 @Override
 public void onClick(View v) {
   if (v.getId() == R.id.btn_obdervable_test1) {
     if (RxBus.hasObservers()) {
       RxBus.send(new TapEvent());
     }
   } else if (v.getId() == R.id.btn_obdervable_test2) {
     if (RxBus.hasObservers()) {
       mRemoteServerEngine
           .loadMoreDataRx(1)
           .subscribeOn(Schedulers.io())
           .observeOn(Schedulers.io())
           .flatMap(refreshModels -> Observable.from(refreshModels))
           .filter(refreshModel -> !refreshModel.title.contains("4"))
           .take(3)
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(
               refreshModel -> {
                 if (RxBus.hasObservers()) {
                   RxBus.send(new RefreshModelEvent(refreshModel));
                 }
               });
     }
   }
 }
 public static void newsList(int id, int page, Subscriber<BaseBean.NewsListBean> subscriber) {
   RxUtils.unsubscribe();
   RxUtils.subscription =
       Network.getTngouApi()
           .getNewsList(id, page)
           .subscribeOn(Schedulers.io())
           .unsubscribeOn(Schedulers.io())
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(subscriber);
 }
Exemplo n.º 6
0
  private void addPostLoadSubscription(final PostAdapter adapter) {
    if (adapter.shouldShowLoadingIndicator()) adapter.showLoadingIndicator();

    Map<String, String> options = adapter.getAdapterOptions();
    String tag = options.get(PaginationAdapter.KEY_TAG);
    final String anchor = options.get(PaginationAdapter.KEY_ANCHOR);
    String nextPage = options.get(PaginationAdapter.KEY_NEXT_PAGE);

    Observable<PostResponse> observable;
    if (tag.equals(mPopularText)) {
      observable = mDataManager.getPopularPosts(nextPage, anchor);
    } else if (tag.equals(mEditorsPicksText)) {
      observable = mDataManager.getEditorsPicksPosts(nextPage, anchor);
    } else {
      observable = mDataManager.getPostsByTag(tag, nextPage, anchor);
    }

    mCompositeSubscription.add(
        observable
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .subscribe(
                new Subscriber<PostResponse>() {
                  @Override
                  public void onCompleted() {}

                  @Override
                  public void onError(Throwable e) {
                    adapter.removeLoadingIndicator();
                    if (adapter.size() == 0) {
                      adapter.showTryAgainCard();
                    } else {
                      Toast.makeText(
                              getActivity(),
                              getString(R.string.error_message_loading_more_posts),
                              Toast.LENGTH_SHORT)
                          .show();
                    }
                    Timber.e("There was an error loading the posts", e);
                  }

                  @Override
                  public void onNext(PostResponse postResponse) {
                    adapter.removeLoadingIndicator();
                    if (adapter.size() == 0 && postResponse.data.records.isEmpty()) {
                      adapter.showReloadCard();
                    } else {
                      if (anchor == null) adapter.setAnchor(postResponse.data.anchorStr);
                      adapter.setNextPage(postResponse.data.nextPage);
                      adapter.addAllItems(postResponse.data.records);
                    }
                  }
                }));
  }
  private void onFavoriteItemSelected(boolean favorited) {
    Observable<Boolean> obsAction;

    if (favorited) {
      obsAction =
          Observable.create(
              (Subscriber<? super Boolean> subscriber) -> {
                try {
                  FavoritesUtils.addToFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem);
                  mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(true).build();
                  subscriber.onNext(true);
                } catch (Exception e) {
                  Timber.w(e, "Unable to add FeedItem to favorites");
                  subscriber.onError(e);
                }
                subscriber.onCompleted();
              });
      obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io());
      bindSubscription(
          obsAction.subscribe(
              result -> {
                if (result) {
                  Toast.makeText(getActivity(), R.string.added_to_favorites, Toast.LENGTH_SHORT)
                      .show();
                }
                configureOverflow(result);
              }));
    } else {
      obsAction =
          Observable.create(
              (Subscriber<? super Boolean> subscriber) -> {
                try {
                  FavoritesUtils.removeFromFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem);
                  mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(false).build();
                  subscriber.onNext(false);
                } catch (Exception e) {
                  Timber.w(e, "Unable to remove FeedItem from favorites");
                  subscriber.onError(e);
                }
                subscriber.onCompleted();
              });
      obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io());
      bindSubscription(
          obsAction.subscribe(
              result -> {
                if (!result) {
                  Toast.makeText(getActivity(), R.string.removed_from_favorites, Toast.LENGTH_SHORT)
                      .show();
                }
                configureOverflow(result);
              }));
    }
  }
Exemplo n.º 8
0
  public CloudPicDataStore(
      ICommonItemService picService,
      ICommentService commentService,
      PicItemDao picItemDao,
      MetaDao metaDao) {
    this.picService = picService;
    this.commentService = commentService;
    this.picItemDao = picItemDao;
    this.metaDao = metaDao;

    this.refreshComment =
        picItems -> {
          CloudPicDataStore.this
              .commentService
              .getDuoshuoCommentList(
                  Joiner.on(",")
                      .join(
                          Lists.transform(
                              picItems, picItem -> Constants.THREAD_PREFIX + picItem.getPicId())))
              .subscribeOn(Schedulers.io())
              .observeOn(Schedulers.io())
              .subscribe(
                  commentCountResponse -> {
                    // TODO: optimize this with tx
                    List<PicItem> picItemList = new ArrayList<PicItem>();
                    for (String key : commentCountResponse.getResponse().keySet()) {
                      CommentCountResponse.CommentCount commentCount =
                          commentCountResponse.getResponse().get(key);
                      Long picId = commentCount.getCommonItemId();
                      logger.info("{}:{}", commentCount.getThreadKey(), commentCount.getCount());
                      PicItem picItem =
                          CloudPicDataStore.this
                              .picItemDao
                              .queryBuilder()
                              .where(PicItemDao.Properties.PicId.eq(picId))
                              .unique();
                      if (picItem != null) {
                        picItem.setCommentCount(commentCount.getCount());
                        picItem.setThreadId(commentCount.getThreadId());
                        picItemList.add(picItem);
                      }
                    }
                    if (picItemList.size() > 0)
                      CloudPicDataStore.this.picItemDao.updateInTx(picItemList);
                  },
                  throwable -> {});
        };
  }
Exemplo n.º 9
0
  private void initData() {
    String token = getIntent().getStringExtra(INTENT_TOKEN);
    String uid = getIntent().getStringExtra(INTENT_UID);
    UserBean userBean = (UserBean) getIntent().getSerializableExtra(INTENT_USER);
    if (userBean == null) {
      ApiServiceHelper.getApiService(Constants.WEIBO_BASE_URL, AccountApiService.class)
          .getUserInfoByUID(token, uid)
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              new Observer<UserBean>() {
                @Override
                public void onCompleted() {}

                @Override
                public void onError(Throwable e) {
                  Log.i("UserDetailActivity", "onError - error : " + e.getMessage());
                }

                @Override
                public void onNext(UserBean userBean) {
                  view.updateView(userBean);
                }
              });
    } else {
      view.updateView(userBean);
    }
  }
Exemplo n.º 10
0
  @Override
  public synchronized Observable<AccessToken> registerForAccessTokenUpdates(String code) {
    Timber.d("registerForAccessTokenUpdates");
    if (loadAccessTokenSubscription == null || loadAccessTokenSubscription.isUnsubscribed()) {
      Timber.d("no loading in progress, starting new one");
      loadAccessTokenSubscription =
          loadAccessTokenObservable(code)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(
                  new DefaultSubscriber<AccessToken>() {

                    @Override
                    public void onError(Throwable throwable) {
                      Timber.e("accessTokenSubject.onError");
                      accessTokenSubject.onError(throwable);
                    }

                    @Override
                    public void onNext(AccessToken data) {
                      Timber.d("accessTokenSubject.onNext: " + data);
                      // Caching accessToken data
                      accessToken = data;
                      accessTokenSubject.onNext(accessToken);
                    }
                  });
    }
    return accessTokenSubject.asObservable();
  }
  private void findSensorId(final Transmitter transmitter, final SensorType sensorType) {
    RelayrSdk.getRelayrApi()
        .getTransmitterDevices(transmitter.id)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<List<TransmitterDevice>>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                showToast(R.string.error_loading_devices);
              }

              @Override
              public void onNext(List<TransmitterDevice> devices) {
                boolean deviceFound = false;

                for (TransmitterDevice device : devices) {
                  if (device.getModel().equals(sensorType.getModel())) {
                    Storage.getRule().sensorId = device.id;
                    saveTransmitterData(transmitter);
                    deviceFound = true;
                  }
                }

                if (!deviceFound) showToast(R.string.error_finding_device);

                switchToEdit(FragmentName.SENSOR);
              }
            });
  }
Exemplo n.º 12
0
 public Observable<List<LocalImage>> getLocalImages() {
   mLocalImages.clear();
   String columns[] =
       new String[] {
         Media._ID,
         Media.BUCKET_ID,
         Media.DATA,
         Media.DISPLAY_NAME,
         Media.TITLE,
         Media.SIZE,
         Media.BUCKET_DISPLAY_NAME
       };
   return Observable.create(
           new Observable.OnSubscribe<Cursor>() {
             @Override
             public void call(Subscriber<? super Cursor> subscriber) {
               L.d(TAG, "currentThread: " + Thread.currentThread().getName());
               Cursor cur = mResolver.query(Media.EXTERNAL_CONTENT_URI, columns, null, null, null);
               subscriber.onNext(cur);
               subscriber.onCompleted();
             }
           })
       .subscribeOn(Schedulers.io())
       .map(
           cursor -> {
             getImagesFromCursor(cursor);
             L.d(TAG, "mLocalImages: " + mLocalImages);
             Collections.reverse(mLocalImages);
             return mLocalImages;
           });
 }
Exemplo n.º 13
0
  @Override
  protected void lazyLoad() {

    Observable.create(
            new Observable.OnSubscribe<List<VBox.VAbstractVideoObject>>() {
              @Override
              public void call(Subscriber<? super List<VBox.VAbstractVideoObject>> subscriber) {
                try {
                  VBox_ServiceGrpc.VBox_ServiceBlockingStub vBoxStub =
                      GrpcManager.getInstance().getStub();
                  VBox.ADBrowseShortVideoReq req =
                      VBox.ADBrowseShortVideoReq.newBuilder()
                          .setTerminalMac(GlobalUtils.getLocalMacAddress(getActivity()))
                          .setReqVideoNum(PAGE_COUNT)
                          .build();
                  VBox.ADBrowseShortVideoRsp res = vBoxStub.browseShortVideo(req);

                  subscriber.onNext(res.getShortVideopageList());

                  //                  测试数据
                  //                    VBox.VAbstractVideoObject ob1 =
                  // VBox.VAbstractVideoObject.newBuilder().setVideoTitle("hua qian
                  // gu").setVideoID(1).setVideoPosterUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png").build();
                  //                    VBox.VAbstractVideoObject ob2 =
                  // VBox.VAbstractVideoObject.newBuilder().setVideoTitle("lang ya
                  // bang").setVideoID(2).setVideoPosterUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png").build();
                  //                    VBox.ADBrowseShortVideoRsp adr =
                  // VBox.ADBrowseShortVideoRsp.newBuilder().addShortVideopage(0,
                  // ob1).addShortVideopage(1, ob2).build();
                  //                    Log.i("xixi", "Res : " +
                  // adr.getShortVideopageList().size());
                  //                    subscriber.onNext(adr.getShortVideopageList());

                } catch (SecurityException | UncheckedExecutionException e) {
                  e.printStackTrace();
                  subscriber.onNext(null);
                }
                subscriber.onCompleted();
              }
            })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Action1<List<VBox.VAbstractVideoObject>>() {
              @Override
              public void call(List<VBox.VAbstractVideoObject> groupList) {
                if (mSwipeRefreshLayout != null) {
                  mSwipeRefreshLayout.setRefreshing(false);
                  mSwipeRefreshLayout.setEnabled(true);
                }
                // 进行显示
                if (groupList == null || groupList.isEmpty()) {
                  isFeedEnd = true;
                  return;
                }
                feedAdapter.setVideoFeed(groupList);
                /* shutdownChannel(); */
              }
            });
  }
Exemplo n.º 14
0
  private void load(final User selectedAssignee) {
    showIndeterminate(R.string.loading_collaborators);
    new GetAssigneesClient(InfoUtils.createRepoInfo(repository))
        .observable()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(activity.<List<User>>bindToLifecycle())
        .subscribe(
            new ObserverAdapter<List<User>>() {
              @Override
              public void onError(Throwable error) {
                dismissProgress();
                Log.d(TAG, "Exception loading collaborators", error);
                ToastUtils.show(activity, error, R.string.error_collaborators_load);
              }

              @Override
              public void onNext(List<User> users) {
                Map<String, User> loadedCollaborators = new TreeMap<>(CASE_INSENSITIVE_ORDER);
                for (User user : users) loadedCollaborators.put(user.login, user);
                collaborators = loadedCollaborators;

                dismissProgress();
                show(selectedAssignee);
              }
            });
  }
Exemplo n.º 15
0
  @Test
  public void testMergeAsyncThenObserveOnLoop() {
    for (int i = 0; i < 500; i++) {
      if (i % 10 == 0) {
        System.out.println("testMergeAsyncThenObserveOnLoop >> " + i);
      }
      // Verify there is no MissingBackpressureException
      int NUM = (int) (RxRingBuffer.SIZE * 4.1);
      AtomicInteger c1 = new AtomicInteger();
      AtomicInteger c2 = new AtomicInteger();

      TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
      Observable<Integer> merged =
          Observable.merge(
              incrementingIntegers(c1).subscribeOn(Schedulers.computation()),
              incrementingIntegers(c2).subscribeOn(Schedulers.computation()));

      merged.observeOn(Schedulers.io()).take(NUM).subscribe(ts);
      ts.awaitTerminalEvent();
      ts.assertNoErrors();
      System.out.println(
          "testMergeAsyncThenObserveOn => Received: "
              + ts.getOnNextEvents().size()
              + "  Emitted: "
              + c1.get()
              + " / "
              + c2.get());
      assertEquals(NUM, ts.getOnNextEvents().size());
    }
  }
Exemplo n.º 16
0
 @Provides
 @Singleton
 BriteDatabase provideDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) {
   BriteDatabase db = sqlBrite.wrapDatabaseHelper(helper, Schedulers.io());
   db.setLoggingEnabled(true);
   return db;
 }
Exemplo n.º 17
0
 public Observable<List<Pair<String, Integer>>> getWordsLevel() {
   return Observable.create(
           new Observable.OnSubscribe<List<Pair<String, Integer>>>() {
             @Override
             public void call(Subscriber<? super List<Pair<String, Integer>>> subscriber) {
               if (s_listWeakReference != null && s_listWeakReference.get() != null) {
                 subscriber.onNext(s_listWeakReference.get());
               } else {
                 try {
                   WordLevelParser wordLevelParser =
                       new WordLevelParser(
                           m_context.getResources().openRawResource(R.raw.nce4_words));
                   List<Pair<String, Integer>> result = wordLevelParser.getWordsLevel();
                   s_listWeakReference = new WeakReference<List<Pair<String, Integer>>>(result);
                   subscriber.onNext(result);
                 } catch (Exception e) {
                   subscriber.onError(e);
                   return;
                 }
               }
               subscriber.onCompleted();
             }
           })
       .subscribeOn(Schedulers.io());
 }
  /**
   * Bind text view to HTML string
   *
   * @param view
   * @param html
   * @param id
   * @return this image getter
   */
  public HttpImageGetter bind(final TextView view, final String html, final Object id) {
    if (TextUtils.isEmpty(html)) return hide(view);

    CharSequence encoded = fullHtmlCache.get(id);
    if (encoded != null) return show(view, encoded);

    encoded = rawHtmlCache.get(id);
    if (encoded == null) {
      if (!html.matches("<[a-z][\\s\\S]*>")) {
        RequestMarkdownDTO markdownDTO = new RequestMarkdownDTO();
        markdownDTO.text = html;
        new GetMarkdownClient(markdownDTO)
            .observable()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                new ObserverAdapter<String>() {
                  @Override
                  public void onNext(String data) {
                    continueBind(view, data, id);
                  }

                  @Override
                  public void onError(Throwable e) {
                    continueBind(view, html, id);
                  }
                });
      } else {
        return continueBind(view, html, id);
      }
    }
    return this;
  }
Exemplo n.º 19
0
 private void loadFromNetwork() {
   Network.getGankApi()
       .getBeautyList(100, 1)
       .subscribeOn(Schedulers.io())
       .map(GankBeautyResultToGankBeauty.getInstance())
       .doOnNext(
           new Action1<List<GankBeauty>>() {
             @Override
             public void call(List<GankBeauty> gankBeauties) {
               Logger.d("Cache data to disk.");
               String gsonStr = new Gson().toJson(gankBeauties);
               mDiskCache.put(DATA_FILE_NAME, gsonStr);
             }
           })
       .subscribe(
           new Action1<List<GankBeauty>>() {
             @Override
             public void call(List<GankBeauty> gankBeauties) {
               Logger.d("Get data from network.");
               mCache.onNext(gankBeauties);
             }
           },
           new Action1<Throwable>() {
             @Override
             public void call(Throwable throwable) {
               throwable.printStackTrace();
             }
           });
 }
  public void loadMoreClientList(int offset, int limit) {
    checkViewAttached();
    getMvpView().showProgressbar(true);
    if (mSubscription != null) mSubscription.unsubscribe();
    mSubscription =
        mDataManager
            .getAllClients(offset, limit)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(
                new Subscriber<Page<Client>>() {
                  @Override
                  public void onCompleted() {
                    getMvpView().showProgressbar(false);
                  }

                  @Override
                  public void onError(Throwable e) {
                    getMvpView().showProgressbar(false);
                    getMvpView()
                        .showFetchingError(
                            "\"Cannot get clients, There might be some" + " problem!\"");
                  }

                  @Override
                  public void onNext(Page<Client> clientPage) {
                    getMvpView().showProgressbar(false);
                    getMvpView().showMoreClientList(clientPage);
                  }
                });
  }
Exemplo n.º 21
0
  public Subscription subscribeData(Observer<List<GankBeauty>> observer) {
    if (mCache == null) {
      mCache = BehaviorSubject.create();
      Observable.create(
              new Observable.OnSubscribe<List<GankBeauty>>() {

                @Override
                public void call(Subscriber<? super List<GankBeauty>> subscriber) {
                  List<GankBeauty> itemList = getDataFromDisk(DATA_FILE_NAME);
                  if (ListUtils.isEmpty(itemList)) {
                    Logger.d("Load data from network");
                    setDataSource(DATA_SOURCE_NETWORK);
                    loadFromNetwork();
                  } else {
                    Logger.d("Load data from disk");
                    setDataSource(DATA_SOURCE_DISK);
                    subscriber.onNext(itemList);
                  }
                }
              })
          .subscribeOn(Schedulers.io())
          .subscribe(mCache);
    } else {
      Logger.d("Load data from memory.");
      setDataSource(DATA_SOURCE_MEMORY);
    }
    return mCache.observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
  }
Exemplo n.º 22
0
  @Override
  public void onBugReportSubmit(final BugReportView.Report report) {
    if (report.includeLogs) {
      lumberYard
          .save()
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              new Subscriber<File>() {
                @Override
                public void onCompleted() {
                  // NO-OP.
                }

                @Override
                public void onError(Throwable e) {
                  Toast.makeText(context, "Couldn't attach the logs.", Toast.LENGTH_SHORT).show();
                  submitReport(report, null);
                }

                @Override
                public void onNext(File logs) {
                  submitReport(report, logs);
                }
              });
    } else {
      submitReport(report, null);
    }
  }
  @Override
  public Observable<List<TMWRule>> loadRemoteRules() {
    return ruleApi
        .getAllRules(new DbSearch(Storage.loadUserId()))
        .subscribeOn(Schedulers.io())
        .map(
            new Func1<DbDocuments<DbRule>, List<TMWRule>>() {
              @Override
              public List<TMWRule> call(DbDocuments<DbRule> docs) {
                new Delete().from(TMWRule.class).execute();

                ActiveAndroid.beginTransaction();
                try {
                  for (DbRule dbRule : docs.getDocuments()) {
                    checkGcmNotification(dbRule);

                    TMWRule rule = DataMapper.toRule(dbRule);
                    rule.save();
                  }
                  ActiveAndroid.setTransactionSuccessful();
                } finally {
                  ActiveAndroid.endTransaction();
                }

                return new Select().from(TMWRule.class).execute();
              }
            });
  }
Exemplo n.º 24
0
  public Observable<Object> ping() {

    return pingService
        .ping()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
  }
Exemplo n.º 25
0
  public void deleteAfterSomeTime(List<QuranRow> remove) {
    if (mPendingRemoval != null) {
      // handle a new delete request when one is already happening by adding those items to delete
      // now and un-subscribing from the old request.
      if (mItemsToRemove != null) {
        remove.addAll(mItemsToRemove);
      }
      cancelDeletion();
    }

    mItemsToRemove = remove;
    mPendingRemoval =
        Observable.timer(DELAY_DELETION_DURATION_IN_MS, TimeUnit.MILLISECONDS)
            .flatMap(
                new Func1<Long, Observable<BookmarkResult>>() {
                  @Override
                  public Observable<BookmarkResult> call(Long aLong) {
                    return removeItemsObservable();
                  }
                })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                new Action1<BookmarkResult>() {
                  @Override
                  public void call(BookmarkResult result) {
                    mPendingRemoval = null;
                    mCachedData = result;
                    if (mFragment != null) {
                      mFragment.onNewData(result);
                    }
                  }
                });
  }
  private void getForecast(double lat, double lng) {
    mForecastManager
        .getWeather(lat, lng)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(
            new Subscriber<com.daryl.stormy.service.CurrentWeather>() {
              @Override
              public void onCompleted() {
                Log.i("forecaster", "success");
              }

              @Override
              public void onError(Throwable e) {
                alertUserAboutError();
                Log.i("forecaster", "error getting forecast: " + e);
              }

              @Override
              public void onNext(com.daryl.stormy.service.CurrentWeather currentWeather) {
                mSummaryLabel.setText(currentWeather.getSummary());
                mHumidityValue.setText("" + currentWeather.getHumidity());
                mTemperatureLabel.setText("" + currentWeather.getTemperature());
                mPrecipValue.setText("" + currentWeather.getPrecipChance());
              }
            });
  }
Exemplo n.º 27
0
  public void search(
      String searchString,
      int rSize,
      int startPageLocation,
      String userIp,
      String size,
      final Callback callback) {
    Log.d("itemListApp", "NetworkManager search");

    imageService
        .search(version, searchString, rSize, startPageLocation, userIp, size)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<NetworkResponseData>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                Log.d("itemListApp", "network onError: " + e.getMessage());
                callback.failure(null);
              }

              @Override
              public void onNext(NetworkResponseData networkResponseData) {
                Log.d("itemListApp", "network success: " + networkResponseData.getClass());
                if (networkResponseData.getResponseData() != null) {
                  callback.success(networkResponseData.getResponseData().getResults(), null);
                }
              }
            });
  }
Exemplo n.º 28
0
  private void populateItems(SkylarkClient client) {

    RecyclerView recycleView = (RecyclerView) findViewById(R.id.setsdetail_recycler_view);

    recycleView.setLayoutManager(new LinearLayoutManager(this));

    final EpisodeAdapter adapter = new EpisodeAdapter(getApplicationContext());
    recycleView.setAdapter(adapter);

    ArrayList<ParcelableItem> parcelableArrayListExtra =
        getIntent().getParcelableArrayListExtra(EXTRA_ITEMS);

    for (Item item : parcelableArrayListExtra) {
      client
          .fetchEpisode(item)
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              new Action1<Episode>() {
                @Override
                public void call(Episode episode) {
                  adapter.add(episode);
                  adapter.notifyItemInserted(adapter.getItemCount());
                }
              });
    }
  }
Exemplo n.º 29
0
  public void onLogout() {
    Settings.getInstance().setUserOnline(false);
    if (SMTHApplication.activeUser != null) {
      SMTHApplication.activeUser.setId("guest");
    }
    UpdateNavigationViewHeader();

    SMTHHelper helper = SMTHHelper.getInstance();
    helper
        .wService
        .logout()
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(
            new Subscriber<AjaxResponse>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                Toast.makeText(MainActivity.this, "退出登录失败!\n" + e.toString(), Toast.LENGTH_LONG)
                    .show();
              }

              @Override
              public void onNext(AjaxResponse ajaxResponse) {
                Toast.makeText(MainActivity.this, ajaxResponse.getAjax_msg(), Toast.LENGTH_LONG)
                    .show();
              }
            });
  }
Exemplo n.º 30
0
 /**
  * @param bytes data to send
  * @return true, if output stream is opened
  */
 public boolean writeData(byte[] bytes) {
   if (logLevel == LogLevel.VERBOSE) Log.d(TAG, "writeData here");
   boolean canWrite = os != null;
   if (canWrite)
     Observable.just(write(bytes))
         .subscribeOn(Schedulers.io())
         .subscribe(
             new Action1<Integer>() {
               @Override
               public void call(Integer integer) {
                 if (logLevel == LogLevel.VERBOSE) Log.d(TAG, integer + " bytes written!!!");
               }
             },
             new Action1<Throwable>() {
               @Override
               public void call(Throwable throwable) {
                 if (logLevel != LogLevel.NONE) {
                   Log.e(TAG, "onError: " + throwable.getMessage());
                   throwable.printStackTrace();
                 }
                 if (onConnectionErrorcallback != null)
                   onConnectionErrorcallback.onError(throwable);
               }
             });
   return canWrite;
 }