Java Code Examples for io.reactivex.disposables.Disposable

The following examples show how to use io.reactivex.disposables.Disposable. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mimi-reader   Source File: NavDrawerFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void postUread(String boardName, long threadId, @NonNull UnreadCountUpdate callback) {
    HistoryTableConnection.fetchPost(boardName, threadId)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SingleObserver<History>() {
                @Override
                public void onSubscribe(Disposable d) {
                    // no op
                }

                @Override
                public void onSuccess(History history) {
                    callback.OnUnreadCountUpdate(history.unreadCount);
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(LOG_TAG, "Error setting unread count badge", e);
                }
            });
}
 
Example 2
Source Project: LocationAware   Source File: LocationAlarmPresenter.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void onDeleteCheckPoint(int adapterPosition) {
  getCheckPointDataSource().deleteCheckPoint(allCheckPoints.get(adapterPosition))
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new CompletableObserver() {
        @Override public void onSubscribe(Disposable d) {

        }

        @Override public void onComplete() {
          allCheckPoints.remove(adapterPosition);
          getView().removeMarker(adapterPosition);
          getView().notifyListAdapter();
        }

        @Override public void onError(Throwable e) {
          getView().showError("Delete Failed");
        }
      });
}
 
Example 3
Source Project: AndroidQuick   Source File: UserManager.java    License: MIT License 6 votes vote down vote up
public void searchAndInsert() {
    Observable.create((ObservableOnSubscribe<String>) emitter -> emitter.onNext("Start"))
            .subscribe(new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String s) {
                    if ("Start".equals(s)) {
                        UserDao.getInstance().createUser("Mike");
                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example 4
public void onInputRecipientAddress(String address, CharSequence amountString) {
        BigDecimal amount = getAmountFromString(amountString);

        if (AdamantAddressValidateHelper.validate(address)) {
            getViewState().dropRecipientAddressError();
            getViewState().setRecipientName(address);
            this.companionId = address;

        } else {
//            getViewState().showRecipientAddressError(R.string.wrong_address);
            this.companionId = null;
        }

        Disposable subscribe = currentFacade
                .getFee()
                .subscribe(
                        fee -> calculate(amount, currentFacade.getBalance(), fee),
                        error -> LoggerHelper.e("amount", error.getMessage(), error)
                );
        subscriptions.add(subscribe);
    }
 
Example 5
Source Project: akarnokd-misc   Source File: RetryWhenPlain.java    License: Apache License 2.0 6 votes vote down vote up
public static <T> Observable<T> retryWhen(Observable<T> source, Function<Observable<Throwable>, Observable<?>> handler) {
    return Observable.<T>defer(() -> {
        PublishSubject<Throwable> errorSignal = PublishSubject.create();

        Observable<?> retrySignal = handler.apply(errorSignal);

        BehaviorSubject<Observable<T>> sources = BehaviorSubject.createDefault(source);

        Disposable d = retrySignal.map(v -> source)
                .subscribe(sources::onNext, sources::onError, sources::onComplete);

        return sources.concatMap(src -> {
            return src
                    .doOnComplete(() -> errorSignal.onComplete())
                    .onErrorResumeNext(e -> {
                errorSignal.onNext(e);
                return Observable.<T>empty();
            });
        }).doFinally(() -> d.dispose());
    });
}
 
Example 6
Source Project: CloudReader   Source File: WelfareViewModel.java    License: Apache License 2.0 6 votes vote down vote up
public MutableLiveData<GankIoDataBean> loadWelfareData() {
    final MutableLiveData<GankIoDataBean> data = new MutableLiveData<>();
    mModel.setData("Girl", "Girl",mPage, 20);
    mModel.getGankIoData(new RequestImpl() {
        @Override
        public void loadSuccess(Object object) {
            GankIoDataBean gankIoDataBean = (GankIoDataBean) object;
            handleImageList(gankIoDataBean);
            data.setValue(gankIoDataBean);
        }

        @Override
        public void loadFailed() {
            if (mPage > 1) {
                mPage--;
            }
            data.setValue(null);
        }

        @Override
        public void addSubscription(Disposable disposable) {
            addDisposable(disposable);
        }
    });
    return data;
}
 
Example 7
Source Project: AndroidBase   Source File: DBPresenter.java    License: Apache License 2.0 6 votes vote down vote up
public void query() {
    getModel().queryForAllSync().subscribe(new Observer<List<City>>() {
        @Override
        public void onSubscribe(Disposable d) {
            getRxManager().add(d);
        }

        @Override
        public void onNext(List<City> data) {
            queryFinish(data);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }

    });

}
 
Example 8
@Override
public void bind(ViewActivity<PortfolioListData> activity) {
    super.bind(activity);
    disposable = new CompositeDisposable();

    Disposable subscribe = Observable.combineLatest(
            portfolioRepository.getPortfolioItems()
                    .toList()
                    .toObservable(),
            purchasesService.monitorPurchases(getActivity()),
            (items, hasPurchases) -> data.withItems(items).withSummaryActive(hasPurchases)
    )
            .subscribe(this::update, RxError::handler);

    disposable.addAll(
            subscribe
    );
}
 
Example 9
private void single() {
    Single.just(1).subscribe(new SingleObserver<Integer>() {
        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, "onSubscribe: " + d.isDisposed());
        }

        @Override
        public void onSuccess(Integer integer) {
            Log.d(TAG, "onSuccess: " + integer);
        }

        @Override
        public void onError(Throwable e) {

        }
    });
}
 
Example 10
Source Project: MBEStyle   Source File: IconShowPresenter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Disposable getWhatsNewIcons() {
    return Observable.fromArray(mView.getResources().getStringArray(R.array.whatsnew))
            .map(new Function<String, IconBean>() {
                @Override
                public IconBean apply(@NonNull String s) throws Exception {
                    IconBean bean = new IconBean();
                    bean.id = mView.getResources().getIdentifier(s, "drawable", BuildConfig.APPLICATION_ID);
                    bean.name = s;

                    return bean;
                }
            }).toList().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<IconBean>>() {
                @Override
                public void accept(List<IconBean> list) throws Exception {
                    mView.onLoadData(list);
                }
            });
}
 
Example 11
Source Project: NovelReader   Source File: BookListPresenter.java    License: MIT License 6 votes vote down vote up
@Override
public void refreshBookList(BookListType type, String tag, int start, int limited) {

    if (tag.equals("全本")){
        tag = "";
    }

    Disposable refreshDispo = getBookListSingle(type, tag, start, limited)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    (beans)-> {
                        mView.finishRefresh(beans);
                        mView.complete();
                    }
                    ,
                    (e) ->{
                        mView.complete();
                        mView.showError();
                        LogUtils.e(e);
                    }
            );
    addDisposable(refreshDispo);
}
 
Example 12
private void loadTemplate() {
    Disposable disposable = Observable
            .fromCallable(() -> {
                SmsCodeRule template = EntityStoreManager.loadEntityFromFile(
                        EntityType.CODE_RULE_TEMPLATE, SmsCodeRule.class
                );
                if (template == null) {
                    template = new SmsCodeRule();
                }
                return template;
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(codeRule -> {
                mCodeRule = codeRule;
                mView.displayCodeRule(mCodeRule);
            });

    mCompositeDisposable.add(disposable);
}
 
Example 13
Source Project: mimi-reader   Source File: ThreadRegistry.java    License: Apache License 2.0 6 votes vote down vote up
public void init() {
    if (threadArray != null) {
        threadArray.clear();
    } else {
        threadArray = new LongSparseArray<>();
    }

    Disposable sub = HistoryTableConnection.fetchHistory(true, 0, false)
            .compose(DatabaseUtils.applySingleSchedulers())
            .subscribe(historyList -> {
                for (History historyDbModel : historyList) {
                    final ThreadRegistryModel t = new ThreadRegistryModel(historyDbModel, Collections.emptyList());
                    final long i = historyDbModel.threadId;

                    Log.d(LOG_TAG, "[refresh] Adding bookmark to registry: size=" + historyDbModel.threadSize);

                    threadArray.append(i, t);
                }
            });
}
 
Example 14
@Override
public void subscribe(ObservableEmitter<DocumentSnapshot> e) throws Exception {
    DocEventListener listener = new DocEventListener(e);
    ListenerRegistration registration = mDocumentReference.addSnapshotListener(listener);
    e.setDisposable(new Disposable() {
        boolean disposed = false;
        @Override
        public void dispose() {
            if (!isDisposed()) {
                registration.remove();
                listener.emitter = null;
                disposed = true;
            }
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    });
}
 
Example 15
Source Project: APlayer   Source File: HeaderAdapter.java    License: GNU General Public License v3.0 6 votes vote down vote up
void disposeLoad(final ViewHolder holder) {
  //
  final ViewGroup parent =
      holder.itemView instanceof ViewGroup ? (ViewGroup) holder.itemView : null;
  if (parent != null) {
    for (int i = 0; i < parent.getChildCount(); i++) {
      final View childView = parent.getChildAt(i);
      if (childView instanceof SimpleDraweeView) {
        final Object tag = childView.getTag();
        if (tag instanceof Disposable) {
          final Disposable disposable = (Disposable) tag;
          if (!disposable.isDisposed()) {
            disposable.dispose();
          }
          childView.setTag(null);
        }
      }
    }
  }
}
 
Example 16
Source Project: RxAndroid-Sample   Source File: ExampleUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAllObservable() {

    Observable.just(0, 1, 2, 3, 4, 0, 6, 0)
            .all(item -> item > 0)
            .subscribe(new SingleObserver<Boolean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onSuccess(Boolean aBoolean) {
                    System.out.println("onNext: " + aBoolean);
                }

                @Override
                public void onError(Throwable e) {

                }
            });
}
 
Example 17
private void refreshBookShelf(BookShelfBean bookShelfBean) {
    WebBookModel.getInstance().getChapterList(bookShelfBean)
            .subscribeOn(scheduler)
            .timeout(1, TimeUnit.MINUTES)
            .flatMap(this::saveBookToShelfO)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SimpleObserver<BookShelfBean>() {

                @Override
                public void onSubscribe(Disposable d) {
                    loadingCount.incrementAndGet();
                    refreshingDisps.add(d);
                }

                @Override
                public void onNext(BookShelfBean value) {
                    whenRefreshNext(bookShelfBean, false);
                }

                @Override
                public void onError(Throwable e) {
                    whenRefreshNext(bookShelfBean, true);
                }
            });
}
 
Example 18
Source Project: MvpRoute   Source File: RxScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 倒计时
 *
 * @param view     倒计时所用到的view
 * @param second   倒计时时长  单位 秒
 * @param listener 倒计时回调
 * @param <T>
 * @return Disposable  返回 Disposable  在Activity的onDestroy方法中
 * disposable.dispose() 取消掉  防止内存泄漏
 * @see CountDownListener  回调接口
 */
public static <T extends View> Disposable countDown(final T view, @IntRange(from = 1) final int second, final CountDownListener<T> listener) {
	if (listener == null || second <= 0) return null;
	return Flowable.intervalRange(0, second + 1, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread())
			.doOnNext(new Consumer<Long>() {
				@Override
				public void accept(Long aLong) throws Exception {
					listener.onCountDownProgress(view, (int) (second - aLong));
				}
			}).doOnComplete(new Action() {
				@Override
				public void run() throws Exception {
					listener.onCountDownComplete(view);
				}
			}).doOnSubscribe(new Consumer<Subscription>() {
				@Override
				public void accept(Subscription subscription) throws Exception {
					listener.onBindCountDown(view);
				}
			}).subscribe();

}
 
Example 19
Source Project: rxjava2-extras   Source File: FlowableInsertTimeout.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(final T t) {
    if (finished) {
        return;
    }
    queue.offer(t);
    final long waitTime;
    try {
        waitTime = timeout.apply(t);
    } catch (Throwable e) {
        Exceptions.throwIfFatal(e);
        // we cancel upstream ourselves because the
        // error did not originate from source
        upstream.cancel();
        onError(e);
        return;
    }
    TimeoutAction<T> action = new TimeoutAction<T>(this, t);
    Disposable d = worker.schedule(action, waitTime, unit);
    DisposableHelper.set(scheduled, d);
    drain();
}
 
Example 20
Source Project: playa   Source File: SearchSuggestPresenter.java    License: MIT License 5 votes vote down vote up
@Override
public void getHotKey() {
    Observable<BaseResponse<List<HotKey>>> observable = dataManager.getHotKey();
    observable.observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .map(new Function<BaseResponse<List<HotKey>>, List<HotKey>>() {
                @Override
                public List<HotKey> apply(@NonNull BaseResponse<List<HotKey>> response)
                        throws Exception {
                    return response.getData();
                }
            }).subscribeWith(new Observer<List<HotKey>>() {
        @Override
        public void onSubscribe(@NonNull Disposable d) {
            disposable = d;
        }

        @Override
        public void onNext(@NonNull List<HotKey> hotKeys) {
            getView().showHotKey(hotKeys);
        }

        @Override
        public void onError(@NonNull Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    });
}
 
Example 21
private synchronized void doUpdate() {
    upIndex++;
    if (upIndex < searchBookBeanList.size()) {
        toBookshelf(searchBookBeanList.get(upIndex))
                .flatMap(this::getChapterList)
                .flatMap(this::saveSearchBookBean)
                .subscribeOn(scheduler)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SearchBookBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                        handler.postDelayed(() -> {
                            if (!d.isDisposed()) {
                                d.dispose();
                                doUpdate();
                            }
                        }, 20 * 1000);
                    }

                    @Override
                    public void onNext(SearchBookBean searchBookBean) {
                        RxBus.get().post(RxBusTag.UP_SEARCH_BOOK, searchBookBean);
                        doUpdate();
                    }

                    @Override
                    public void onError(Throwable e) {
                        doUpdate();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
 
Example 22
Source Project: CloudReader   Source File: FilmDetailActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void initRxBus() {
    Disposable subscribe = RxBus.getDefault().toObservable(RxCodeConstants.JUMP_CURRENT_POSITION, Integer.class)
            .subscribe(new Consumer<Integer>() {
                @Override
                public void accept(Integer integer) throws Exception {
                    bindingContentView.xrvImages.smoothScrollToPosition(integer);
                }
            });
    addSubscription(subscribe);
}
 
Example 23
Source Project: WanAndroid   Source File: ArticlesPresenter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void autoLogin(String userName, String password) {
    Disposable disposable = loginDataRepository.getRemoteLoginData(userName, password, LoginType.TYPE_LOGIN)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<LoginData>() {

                @Override
                public void onNext(LoginData value) {
                    if (view.isActive() && value.getErrorCode() == -1) {
                        view.showAutoLoginFail();
                    }
                }

                @Override
                public void onError(Throwable e) {
                    if (view.isActive()) {
                        view.showAutoLoginFail();
                    }
                }

                @Override
                public void onComplete() {

                }
            });
    compositeDisposable.add(disposable);
}
 
Example 24
private void queryCurrentCash(){
    cardFactory.getCurrentCash(new Observer<CardBasic>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onNext(CardBasic value) {
            if(null != value && !TextUtils.isEmpty(value.getCash())) {
                tvMeCash.setText("¥" + value.getCash());
                mCardNum = value.getCardNum();
            }else{
                tvMeCash.setText("获取失败");
            }
        }
        @Override
        public void onError(Throwable e) {
            if(e != null && !TextUtils.isEmpty(e.getMessage())) {
                LogUtils.e(e.toString());
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            tvMeCash.setText("获取失败");
        }
        @Override
        public void onComplete() {
        }
    });
}
 
Example 25
Source Project: RxBus   Source File: RxBus.java    License: Apache License 2.0 5 votes vote down vote up
private <T> void subscribe(final Object subscriber,
                           final String tag,
                           final boolean isSticky,
                           final Scheduler scheduler,
                           final Callback<T> callback) {
    Utils.requireNonNull(subscriber, tag, callback);

    final Class<T> typeClass = Utils.getTypeClassFromParadigm(callback);

    final Consumer<T> onNext = new Consumer<T>() {
        @Override
        public void accept(T t) {
            callback.onEvent(t);
        }
    };

    if (isSticky) {
        final TagMessage stickyEvent = CacheUtils.getInstance().findStickyEvent(typeClass, tag);
        if (stickyEvent != null) {
            Flowable<T> stickyFlowable = Flowable.create(new FlowableOnSubscribe<T>() {
                @Override
                public void subscribe(FlowableEmitter<T> emitter) {
                    emitter.onNext(typeClass.cast(stickyEvent.mEvent));
                }
            }, BackpressureStrategy.LATEST);
            if (scheduler != null) {
                stickyFlowable = stickyFlowable.observeOn(scheduler);
            }
            Disposable stickyDisposable = FlowableUtils.subscribe(stickyFlowable, onNext, mOnError);
            CacheUtils.getInstance().addDisposable(subscriber, stickyDisposable);
        } else {
            Utils.logW("sticky event is empty.");
        }
    }
    Disposable disposable = FlowableUtils.subscribe(
            toFlowable(typeClass, tag, scheduler), onNext, mOnError
    );
    CacheUtils.getInstance().addDisposable(subscriber, disposable);
}
 
Example 26
Source Project: okhttp-OkGo   Source File: RxBitmapActivity.java    License: Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.requestImage)
public void requestImage(View view) {
    ServerApi.getBitmap("aaa", "bbb")//
            .subscribeOn(Schedulers.io())//
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    showLoading();
                }
            })//
            .observeOn(AndroidSchedulers.mainThread())//
            .subscribe(new Observer<Response<Bitmap>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(@NonNull Response<Bitmap> response) {
                    handleResponse(response);
                    imageView.setImageBitmap(response.body());
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();            //请求失败
                    handleError(null);
                    showToast("请求失败");
                }

                @Override
                public void onComplete() {
                    dismissLoading();
                }
            });
}
 
Example 27
Source Project: JD-Test   Source File: MainDataManager.java    License: Apache License 2.0 5 votes vote down vote up
public<S> Disposable getData(DisposableObserver<S> consumer , final Class<S> clazz , final String fillName) {
    return Observable.create(new ObservableOnSubscribe<S>() {
        @Override
        public void subscribe(ObservableEmitter<S> e) throws Exception {
            InputStream is = getContext().getAssets().open(fillName);
            String text = FillUtil.readTextFromFile(is);
            Gson gson = new Gson();
            e.onNext(gson.fromJson(text, clazz));
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(consumer);
}
 
Example 28
Source Project: RxAndroid-Sample   Source File: ExampleUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testObserveOnObservable() {


    Observable.just("A", "BB", "CCC", "DDDD", "EEEEE", "FFFFFF") // UI
            .map(str -> str.length()) // UI
            .observeOn(Schedulers.computation()) //Changing the thread
            .map(length -> 2 * length)
            .subscribe(new Observer<Integer>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Integer integer) {
                    System.out.println("2 * length of string: " + integer);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example 29
Source Project: RxEasyHttp   Source File: DownloadRequest.java    License: Apache License 2.0 5 votes vote down vote up
public <T> Disposable execute(CallBack<T> callBack) {
    return (Disposable) build().generateRequest().compose(new ObservableTransformer<ResponseBody, ResponseBody>() {
        @Override
        public ObservableSource<ResponseBody> apply(@NonNull Observable<ResponseBody> upstream) {
            if (isSyncRequest) {
                return upstream;//.observeOn(AndroidSchedulers.mainThread());
            } else {
                return upstream.subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(Schedulers.computation());
            }
        }
    }).compose(new HandleErrTransformer()).retryWhen(new RetryExceptionFunc(retryCount, retryDelay, retryIncreaseDelay))
            .subscribeWith(new DownloadSubscriber(context, savePath, saveName, callBack));
}
 
Example 30
Source Project: java-unified-sdk   Source File: AVCloudQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testQuerySubclass() throws  Exception {
  testSucceed = false;
  latch = new CountDownLatch(1);

  String cql = "select * from Student";
  AVCloudQuery.executeInBackground(cql, Student.class).subscribe(new Observer<AVCloudQueryResult>() {
    public void onSubscribe(Disposable disposable) {

    }

    public void onNext(AVCloudQueryResult avCloudQueryResult) {
      for (AVObject u: avCloudQueryResult.getResults()) {
        System.out.println(u.toString());
      }
      testSucceed = true;
      latch.countDown();
    }

    public void onError(Throwable throwable) {
      latch.countDown();
    }

    public void onComplete() {

    }
  });
  latch.await();
  assertTrue(testSucceed);
}