io.reactivex.disposables.Disposable Java Examples

The following examples show how to use io.reactivex.disposables.Disposable. 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 File: HeaderAdapter.java    From APlayer with 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 #2
Source File: BookListPresenter.java    From NovelReader with 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 #3
Source File: WelfareViewModel.java    From CloudReader with 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 #4
Source File: RetryWhenPlain.java    From akarnokd-misc with 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 #5
Source File: SendFundsPresenter.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: DBPresenter.java    From AndroidBase with 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 #7
Source File: RuleEditPresenter.java    From XposedSmsCode with GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source File: IconShowPresenter.java    From MBEStyle with 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 #9
Source File: UserManager.java    From AndroidQuick with 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 #10
Source File: ThreadRegistry.java    From mimi-reader with 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 #11
Source File: FirestoreDocumentOnSubscribe.java    From Track-My-Location with GNU General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: ExampleUnitTest.java    From RxAndroid-Sample with 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 #13
Source File: OperatorActivity.java    From android-open-framework-analysis with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: BookRefreshModelImpl.java    From HaoReader with GNU General Public License v3.0 6 votes vote down vote up
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 #15
Source File: RxScheduler.java    From MvpRoute with 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 #16
Source File: StockViewModel.java    From Building-Professional-Android-Applications with MIT License 6 votes vote down vote up
@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 #17
Source File: FlowableInsertTimeout.java    From rxjava2-extras with 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 #18
Source File: LocationAlarmPresenter.java    From LocationAware with 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 #19
Source File: NavDrawerFragment.java    From mimi-reader with 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 #20
Source File: SearchSuggestPresenter.java    From playa with 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
Source File: ChatStorageTest.java    From adamant-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void concurrentOneProducerOneConsumer() {
    ChatsStorage chatsStorage = new ChatsStorage();

    Flowable<AdamantBasicMessage> producer = provideProducer(chatsStorage);
    Flowable<Integer> consumer = provideConsumer(chatsStorage, CHAT_COUNT);

    Disposable producerSubscription = producer.subscribe();
    subscriptions.add(producerSubscription);

    Integer size = consumer.blockingFirst();

    Assert.assertEquals(CHAT_COUNT, (int) size);
}
 
Example #22
Source File: MergeExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 5 votes vote down vote up
private Observer<String> getObserver() {
    return new Observer<String>() {

        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, " onSubscribe : " + d.isDisposed());
        }

        @Override
        public void onNext(String value) {
            textView.append(" onNext : value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onNext : value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onComplete");
        }
    };
}
 
Example #23
Source File: AVQueryTest.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public void testGetInBackgroundWithIncludePointer() throws Exception {
  AVObject current = AVObject.createWithoutData("Student", currentObjectId);
  final AVObject target = new AVObject("Student");
  target.put("friend", current);
  target.save();
  AVQuery query = new AVQuery("Student");
  query.include("friend");
  query.getInBackground(target.getObjectId()).subscribe(new Observer<AVObject>() {
    @Override
    public void onSubscribe(Disposable disposable) {

    }

    @Override
    public void onNext(AVObject o) {
      AVObject friend = o.getAVObject("friend");
      testSucceed = "Automatic Tester".equals(friend.get("name"));
      latch.countDown();
    }

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

    @Override
    public void onComplete() {

    }
  });
  latch.await();
  target.delete();
  assertTrue(testSucceed);
}
 
Example #24
Source File: SingleLife.java    From rxjava-RxLife with Apache License 2.0 5 votes vote down vote up
public final Disposable subscribe(final Consumer<? super T> onSuccess, final Consumer<? super Throwable> onError) {
    ObjectHelper.requireNonNull(onSuccess, "onSuccess is null");
    ObjectHelper.requireNonNull(onError, "onError is null");

    ConsumerSingleObserver<T> observer = new ConsumerSingleObserver<T>(onSuccess, onError);
    subscribe(observer);
    return observer;
}
 
Example #25
Source File: PaasClientTest.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public void testCreateUploadToken() throws Exception {

      JSONObject fileObject = new JSONObject();
      StorageClient storageClient = PaasClient.getStorageClient();
      storageClient.newUploadToken(fileObject).subscribe(new Observer<FileUploadToken>() {
        public void onComplete() {

        }

        public void onError(Throwable throwable) {
          System.out.println("failed! cause: " + throwable);
          testSucceed = true;
          latch.countDown();
        }

        public void onNext(FileUploadToken fileUploadToken) {
          System.out.println(fileUploadToken);

          latch.countDown();
        }
        public void onSubscribe(Disposable disposable) {
          ;
        }
      });
      latch.await();
      assertTrue(testSucceed);
  }
 
Example #26
Source File: CommonObserver.java    From MvpRxJavaRetrofitOkhttp with MIT License 5 votes vote down vote up
@Override
public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
    disposable = d;
    if (!NetworkUtil.isNetworkAvailable(context)) {
        LogUtils.e(TAG, "网络不可用");
    } else {
        LogUtils.e(TAG, "网络可用");
    }
}
 
Example #27
Source File: MyObserver.java    From Reactive-Programming-With-Java-9 with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	
	Observable<Long>observable=Observable.rangeLong(1l,3l);
	Observer< Long> observer=new Observer<Long>() {

		@Override
		public void onComplete() {
			// TODO Auto-generated method stub
			System.out.println("on complete");
			
		}

		@Override
		public void onError(Throwable throwable) {
			// TODO Auto-generated method stub
			throwable.printStackTrace();
			
		}

		@Override
		public void onNext(Long value) {
			// TODO Auto-generated method stub
			System.out.println(""+value);
			
		}

		@Override
		public void onSubscribe(Disposable disposable) {
			// TODO Auto-generated method stub
			System.out.println(disposable.isDisposed());
			disposable.dispose();
			
		}
	};
	observable.subscribe(observer);
	
}
 
Example #28
Source File: FileDemoActivity.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public void testUploaderExternelUrlWithObserver() throws Exception {
  AVFile file = new AVFile("test", "http://cms-bucket.ws.126.net/2020/0401/8666ec9dp00q83fid008oc000m801n8c.png");
  Observable<AVFile> result = file.saveInBackground();
  result.subscribe(new Observer<AVFile>() {
    @Override
    public void onSubscribe(Disposable d) {
      ;
    }

    @Override
    public void onNext(AVFile avFile) {
      log("Thread:" + Thread.currentThread().getId());
      log("保存了一个File:" + avFile.getObjectId());
      Toast.makeText(FileDemoActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(Throwable e) {
      Toast.makeText(FileDemoActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onComplete() {

    }
  });
}
 
Example #29
Source File: UpLastChapterModel.java    From a with GNU General Public License v3.0 5 votes vote down vote up
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 #30
Source File: AVPushTest.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public void testPushFlowControl() throws Exception {
  AVPush push = new AVPush();
  Map<String, Object> pushData = new HashMap<>();
  pushData.put("alert", "push message to android device directly");
  push.setPushToAndroid(true);
  push.setData(pushData);
  push.setFlowControl( 200);
  assertEquals(push.getFlowControl(), 1000);

  final CountDownLatch latch = new CountDownLatch(1);
  testSucceed = false;
  push.sendInBackground().subscribe(new Observer<JSONObject>() {
    @Override
    public void onSubscribe(Disposable d) {
    }

    @Override
    public void onNext(JSONObject jsonObject) {
      System.out.println("推送成功" + jsonObject);
      testSucceed = true;
      latch.countDown();
    }

    @Override
    public void onError(Throwable e) {
      e.printStackTrace();
      System.out.println("推送失败,错误信息:" + e.getMessage());
      latch.countDown();
    }

    @Override
    public void onComplete() {
    }
  });
  latch.await();
  assertTrue(testSucceed);
}