io.reactivex.schedulers.Schedulers Java Examples
The following examples show how to use
io.reactivex.schedulers.Schedulers.
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: DataManager.java From okuki with Apache License 2.0 | 6 votes |
public void loadMore() { if (!loading.get()) { setIsLoading(true); doLoad(pageSize, items.size()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(error -> setIsLoading(false)) .subscribe( list -> { if (!list.isEmpty()) { items.addAll(list); } setIsLoading(false); }, Errors.log()); } }
Example #2
Source File: WaitPresenter.java From Readhub with Apache License 2.0 | 6 votes |
@Override public void getData() { WaitDataBase.getDatabase().waitDao().findAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Wait>>() { @Override public void accept(List<Wait> waitList) throws Exception { if (isRefresh) { mSwipeRefreshLayout.setRefreshing(false); isRefresh = false; iTopicView.setRefresh(waitList); } else { iTopicView.hideLoading(); iTopicView.getTopicEntity(waitList); } } }); }
Example #3
Source File: MarketTickerRepository.java From bitshares_wallet with MIT License | 6 votes |
private void fetchFromNetwork(final LiveData<List<BitsharesMarketTicker>> dbSource) { result.addSource(dbSource, newData -> result.setValue(Resource.loading(newData))); // 向远程获取数据,并进行存储 Flowable.just(0) .subscribeOn(Schedulers.io()) .map(integer -> { // 获取asset list fetchMarketTicker(); return 0; }).observeOn(AndroidSchedulers.mainThread()) .subscribe(retCode -> { LiveData<List<BitsharesMarketTicker>> listLiveData = bitsharesDao.queryMarketTicker(); result.removeSource(dbSource); result.addSource(listLiveData, newData -> result.setValue(Resource.success(newData))); }, throwable -> { result.removeSource(dbSource); result.addSource(dbSource, newData -> result.setValue(Resource.error(throwable.getMessage(), newData))); }); }
Example #4
Source File: FourChanConnector.java From mimi-reader with Apache License 2.0 | 6 votes |
@Override public Single<List<ChanArchive>> fetchArchives() { return api.fetchArchives("https://raw.githubusercontent.com/ccd0/4chan-x/master/src/Archive/archives.json") .observeOn(Schedulers.io()) .toObservable() .flatMapIterable((Function<List<FourChanArchive>, Iterable<FourChanArchive>>) fourChanArchives -> fourChanArchives) .flatMap((Function<FourChanArchive, ObservableSource<ChanArchive>>) fourChanArchive -> { final ChanArchive chanArchive = new ChanArchive.Builder() .boards(fourChanArchive.getBoards()) .files(fourChanArchive.getFiles()) .domain(fourChanArchive.getDomain()) .http(fourChanArchive.getHttp()) .https(fourChanArchive.getHttps()) .software(fourChanArchive.getSoftware()) .uid(fourChanArchive.getUid()) .name(fourChanArchive.getName()) .reports(fourChanArchive.getReports()) .build(); return Observable.just(chanArchive); }) .toList(); }
Example #5
Source File: MainActivity.java From Android-Allocine-Api with Apache License 2.0 | 6 votes |
public void execute() { final AllocineApi allocineApi = new AllocineApi(okHttpClient); allocineApi.movieList(AllocineApi.MovieListFilter.NOW_SHOWING, AllocineApi.Profile.SMALL, AllocineApi.MovieListOrder.TOPRANK, 20, 1) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Movie>>() { @Override public void accept(List<Movie> movies) throws Exception { textView.setText(movies.toString()); Log.d("MainActivity", movies.toString()); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Log.e("tag", throwable.getLocalizedMessage(), throwable); } }); }
Example #6
Source File: SendFragment.java From bitshares_wallet with MIT License | 6 votes |
private void processGetTransferToId(final String strAccount, final TextView textViewTo) { Flowable.just(strAccount) .subscribeOn(Schedulers.io()) .map(accountName -> { account_object accountObject = BitsharesWalletWraper.getInstance().get_account_object(accountName); if (accountObject == null) { throw new ErrorCodeException(ErrorCode.ERROR_NO_ACCOUNT_OBJECT, "it can't find the account"); } return accountObject; }).observeOn(AndroidSchedulers.mainThread()) .subscribe(accountObject -> { if (getActivity() != null && getActivity().isFinishing() == false) { textViewTo.setText("#" + accountObject.id.get_instance()); } }, throwable -> { if (throwable instanceof NetworkStatusException || throwable instanceof ErrorCodeException) { if (getActivity() != null && getActivity().isFinishing() == false) { textViewTo.setText("#none"); } } else { throw Exceptions.propagate(throwable); } }); }
Example #7
Source File: FunctionActivity.java From alpha-wallet-android with MIT License | 6 votes |
private void getAttrs() { try { attrs = viewModel.getAssetDefinitionService().getTokenAttrs(token, tokenId, 1); //add extra tokenIds if required addMultipleTokenIds(attrs); } catch (Exception e) { e.printStackTrace(); } // Fetch attributes local to this action and add them to the injected token properties Map<String, TSAction> functions = viewModel.getAssetDefinitionService().getTokenFunctionMap(token.tokenInfo.chainId, token.getAddress()); action = functions.get(actionMethod); List<Attribute> localAttrs = (action != null && action.attributes != null) ? new ArrayList<>(action.attributes.values()) : null; viewModel.getAssetDefinitionService().resolveAttrs(token, tokenIds, localAttrs) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onAttr, this::onError, () -> displayFunction(attrs.toString())) .isDisposed(); }
Example #8
Source File: ShotLikeListPresenter.java From Protein with Apache License 2.0 | 6 votes |
@Override public void fetchMoreData() { if (TextUtils.isEmpty(getNextPageUrl())) return; view.showLoadingMore(true); repository.listShotLikesForUserOfNextPage(getNextPageUrl()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(((LifecycleProvider<FragmentEvent>) view).bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(listResponse -> { view.showLoadingMore(false); view.showMoreData(generateEpoxyModels(listResponse.body())); setNextPageUrl(new PageLinks(listResponse).getNext()); }, throwable -> { view.showLoadingMore(false); view.showSnackbar(throwable.getMessage()); throwable.printStackTrace(); }); }
Example #9
Source File: RxCommandTest.java From RxCommand with MIT License | 6 votes |
@Test public void executionObservables_notAllowingConcurrent_onlyExecutionOnce() { RxCommand<String> command = RxCommand.create(o -> Observable.just((String) o) .subscribeOn(Schedulers.newThread()) .delay(10, TimeUnit.MILLISECONDS) ); TestObserver<Observable<String>> testObserver = new TestObserver<>(); command.executionObservables().subscribe(testObserver); command.execute("1"); command.execute("2"); command.execute("3"); // wait try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } testObserver.assertValueCount(1); testObserver.assertNoErrors(); testObserver.assertNotComplete(); }
Example #10
Source File: RxProcess.java From RxShell with Apache License 2.0 | 6 votes |
@SuppressLint("NewApi") public Single<Boolean> isAlive() { if (RXSDebug.isDebug()) Timber.tag(TAG).v("isAlive()"); return Single .create((SingleEmitter<Boolean> emitter) -> { if (ApiWrap.hasOreo()) { emitter.onSuccess(process.isAlive()); } else { try { process.exitValue(); emitter.onSuccess(false); } catch (IllegalThreadStateException e) { emitter.onSuccess(true); } } }) .subscribeOn(Schedulers.io()); }
Example #11
Source File: RxUtils.java From Aurora with Apache License 2.0 | 6 votes |
public static <T> ObservableTransformer<T, T> applySchedulers(final IView view,final boolean isLoadMore) { return new ObservableTransformer<T, T>() { @Override public Observable<T> apply(Observable<T> observable) { return observable.subscribeOn(Schedulers.io()) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(@NonNull Disposable disposable) throws Exception { if (!isLoadMore){ view.showLoading(); } } }) .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate(new Action() { @Override public void run() { view.hideLoading();//隐藏进度条 } }).compose(RxLifecycleUtils.bindToLifecycle(view)); } }; }
Example #12
Source File: TopicListModel.java From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 | 6 votes |
@Override public void removeTopic(ThreadPageInfo info, final OnHttpCallBack<String> callBack) { initFieldMap(); mFieldMap.put("page", String.valueOf(info.getPage())); mFieldMap.put("tidarray", String.valueOf(info.getTid())); mService.post(mFieldMap) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(getLifecycleProvider().<String>bindUntilEvent(FragmentEvent.DETACH)) .subscribe(new BaseSubscriber<String>() { @Override public void onNext(@NonNull String s) { if (s.contains("操作成功")) { callBack.onSuccess("操作成功!"); } else { callBack.onError("操作失败!"); } } }); }
Example #13
Source File: MyService.java From BetterWay with Apache License 2.0 | 6 votes |
/** * 初始化日期 */ private void initDates() { io.reactivex.Observable.create(new ObservableOnSubscribe<List<Schedule>>() { @Override public void subscribe(ObservableEmitter<List<Schedule>> e) throws Exception { MainModel mainModel = MainModel.getInstance(); List<Schedule> schedules = mainModel.inquiryAllSchedule(getApplication()); if (schedules.size() != 0) { e.onNext(schedules); } } }).observeOn(Schedulers.io()) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Schedule>>() { @Override public void accept(List<Schedule> list) throws Exception { for (Schedule schedule : list) { dates.add(schedule.getStartTime()); LogUtil.i(TAG, dates.size() + "个"); } } }); }
Example #14
Source File: CreateTransactionInteract.java From Upchain-wallet with GNU Affero General Public License v3.0 | 6 votes |
public Single<String> createTransaction(ETHWallet from, BigInteger gasPrice, BigInteger gasLimit, String data, String password) { final Web3j web3j = Web3j.build(new HttpService(networkRepository.getDefaultNetwork().rpcServerUrl)); return networkRepository.getLastTransactionNonce(web3j, from.address) .flatMap(nonce -> getRawTransaction(nonce, gasPrice, gasLimit, BigInteger.ZERO, data)) .flatMap(rawTx -> signEncodeRawTransaction(rawTx, password, from, networkRepository.getDefaultNetwork().chainId)) .flatMap(signedMessage -> Single.fromCallable( () -> { EthSendTransaction raw = web3j .ethSendRawTransaction(Numeric.toHexString(signedMessage)) .send(); if (raw.hasError()) { throw new Exception(raw.getError().getMessage()); } return raw.getTransactionHash(); })).subscribeOn(Schedulers.io()); }
Example #15
Source File: BlueJayService.java From xDrip-plus with GNU General Public License v3.0 | 6 votes |
boolean sendOtaChunk(final UUID uuid, final byte[] bytes) { if (I.connection == null || !I.isConnected) return false; I.connection.writeCharacteristic(uuid, bytes) .observeOn(Schedulers.io()) .subscribeOn(Schedulers.io()) .subscribe( characteristicValue -> { if (D) UserError.Log.d(TAG, "Wrote record request request: " + bytesToHex(characteristicValue)); busy = false; }, throwable -> { UserError.Log.e(TAG, "Failed to write record request: " + throwable); if (throwable instanceof BleGattCharacteristicException) { final int status = ((BleGattCharacteristicException) throwable).getStatus(); UserError.Log.e(TAG, "Got status message: " + Helper.getStatusName(status)); } else { if (throwable instanceof BleDisconnectedException) { changeState(CLOSE); } UserError.Log.d(TAG, "Throwable in Record End write: " + throwable); } }); return true; // only that we didn't fail in setup }
Example #16
Source File: RxPaperBookTest.java From RxPaper2 with MIT License | 6 votes |
@Test public void testDestroy() throws Exception { RxPaperBook book = RxPaperBook.with("DESTROY", Schedulers.trampoline()); final String key = "hello"; final String key2 = "you"; final ComplexObject value = ComplexObject.random(); book.write(key, value).subscribe(); book.write(key2, value).subscribe(); final TestObserver<Void> destroySubscriber = book.destroy().test(); destroySubscriber.awaitTerminalEvent(); destroySubscriber.assertComplete(); destroySubscriber.assertNoErrors(); destroySubscriber.assertValueCount(0); Assert.assertFalse(book.book.contains(key)); Assert.assertFalse(book.book.contains(key2)); }
Example #17
Source File: WalletsViewModel.java From alpha-wallet-android with MIT License | 5 votes |
public void swipeRefreshWallets() { //check for updates //check names first disposable = fetchWalletsInteract.fetch().toObservable() .flatMap(Observable::fromArray) .forEach(wallet -> ensResolver.resolveEnsName(wallet.address) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(ensName -> updateOnName(wallet, ensName), this::onError)); updateWallets(); }
Example #18
Source File: NoteDataRepository.java From CrazyDaily with Apache License 2.0 | 5 votes |
@Override public Flowable<List<NoteEntity>> getNoteList() { return Flowable.just(NoteEntity.FLAG_SUBMIT) .observeOn(Schedulers.io()) .flatMap(this::getNoteListByDB) .compose(RxTransformerUtil.normalTransformer()); }
Example #19
Source File: SetOperationTests.java From java-unified-sdk with Apache License 2.0 | 5 votes |
public SetOperationTests(String testName) { super(testName); AppConfiguration.config(true, new AppConfiguration.SchedulerCreator() { public Scheduler create() { return Schedulers.newThread(); } }); Configure.initializeRuntime(); }
Example #20
Source File: RxParser.java From tysq-android with GNU General Public License v3.0 | 5 votes |
/** * 拆壳 * * @param <T> * @return */ public static <T> ObservableTransformer<RespData<T>, T> handleObservableDataResult() { return new ObservableTransformer<RespData<T>, T>() { @Override public ObservableSource<T> apply(Observable<RespData<T>> upstream) { return upstream .map(new TransToData<T>()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; }
Example #21
Source File: MenuAdapter.java From commcare-android with Apache License 2.0 | 5 votes |
private void setupBadgeView(View badgeView, MenuDisplayable menuDisplayable, int position) { badgeView.setVisibility(View.GONE); badgeView.setTag(position); if (badgeCache.get(position) != null) { updateBadgeView(badgeView, badgeCache.get(position)); } else { Text badgeTextObject = menuDisplayable.getRawBadgeTextObject(); if (badgeTextObject != null) { Set<String> instancesNeededByBadgeCalculation = (new InstanceNameAccumulatingAnalyzer()).accumulate(badgeTextObject); context.attachDisposableToLifeCycle( menuDisplayable.getTextForBadge(asw.getRestrictedEvaluationContext(menuDisplayable.getCommandID(), instancesNeededByBadgeCalculation)) .subscribeOn(Schedulers.single()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(badgeText -> { // Make sure that badgeView corresponds to the right position and update it if (((int)badgeView.getTag()) == position) { updateBadgeView(badgeView, badgeText); } }, throwable -> UserfacingErrorHandling.createErrorDialog(context, throwable.getLocalizedMessage(), true) ) ); } else { updateBadgeView(badgeView, ""); } } }
Example #22
Source File: RxAdapterHelper.java From MultiTypeRecyclerViewAdapter with Apache License 2.0 | 5 votes |
@SuppressLint("CheckResult") @Override protected void startRefresh(HandleBase<MultiHeaderEntity> refreshData) { Flowable.just(refreshData) .onBackpressureDrop() .observeOn(Schedulers.io()) .map(handleBase -> handleRefresh(handleBase.getNewData(), handleBase.getNewHeader(), handleBase.getNewFooter(), handleBase.getLevel(), handleBase.getRefreshType())) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleResult); }
Example #23
Source File: MapStageFactoryTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Test public void create() throws ExecutionException, InterruptedException { Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .subscribeOn(Schedulers.computation()); List<String> list = ReactiveStreams.fromPublisher(flowable) .filter(i -> i < 4) .map(this::square) .map(this::asString) .toList() .run().toCompletableFuture().get(); assertThat(list).containsExactly("1", "4", "9"); }
Example #24
Source File: BaiduNaviDao.java From AssistantBySDK with Apache License 2.0 | 5 votes |
/** * 同步收藏地址 **/ public void sync() { Single.just(0) .observeOn(Schedulers.io()) .doOnSuccess(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Exception { AndroidChatRobotBuilder.get().robot().actionTargetAccessor().sync(instance); } }) .subscribe(); }
Example #25
Source File: OnlineMusicActivity.java From YCAudioPlayer with Apache License 2.0 | 5 votes |
private void getData(final int offset) { OnLineMusicModel model = OnLineMusicModel.getInstance(); model.getSongListInfo(OnLineMusicModel.METHOD_GET_MUSIC_LIST, type, MUSIC_LIST_SIZE, String.valueOf(offset)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<OnlineMusicList>() { @Override public void accept(OnlineMusicList onlineMusicList) throws Exception { if (onlineMusicList == null || onlineMusicList.getSong_list() == null || onlineMusicList.getSong_list().size() == 0) { return; } addHeader(onlineMusicList); adapter.addAll(onlineMusicList.getSong_list()); recyclerView.showRecycler(); setOnLineMusic(onlineMusicList); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { if (throwable instanceof RuntimeException) { // 歌曲全部加载完成 recyclerView.showError(); return; } if (offset == 0) { recyclerView.showError(); } else { ToastUtils.showRoundRectToast(Utils.getApp().getResources().getString(R.string.load_fail)); } } }, new Action() { @Override public void run() throws Exception { } }); }
Example #26
Source File: WindmillPerf.java From akarnokd-misc with Apache License 2.0 | 5 votes |
@Setup public void setup() { sg1 = reactor.core.scheduler.Schedulers.newSingle("A"); sg2 = reactor.core.scheduler.Schedulers.newSingle("B"); Integer[] arr = new Integer[count]; Arrays.fill(arr, 777); flx = Flux.fromArray(arr).subscribeOn(sg1).publishOn(sg2); }
Example #27
Source File: ChapterSeven.java From RxJava2Demo with Apache License 2.0 | 5 votes |
public static void demo3() { Flowable.create(new FlowableOnSubscribe<Integer>() { @Override public void subscribe(FlowableEmitter<Integer> emitter) throws Exception { Log.d(TAG, "emit 1"); emitter.onNext(1); Log.d(TAG, "emit 2"); emitter.onNext(2); Log.d(TAG, "emit 3"); emitter.onNext(3); Log.d(TAG, "emit complete"); emitter.onComplete(); } }, BackpressureStrategy.ERROR).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Integer>() { @Override public void onSubscribe(Subscription s) { Log.d(TAG, "onSubscribe"); mSubscription = s; } @Override public void onNext(Integer integer) { Log.d(TAG, "onNext: " + integer); } @Override public void onError(Throwable t) { Log.w(TAG, "onError: ", t); } @Override public void onComplete() { Log.d(TAG, "onComplete"); } }); }
Example #28
Source File: AnimeDetailBean.java From DanDanPlayForAndroid with MIT License | 5 votes |
public static void getAnimaDetail(String animaId, CommJsonObserver<AnimeDetailBean> observer, NetworkConsumer consumer){ RetroFactory.getInstance().getAnimaDetail(animaId) .doOnSubscribe(consumer) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); }
Example #29
Source File: FragmentLikeIllustHorizontal.java From Pixiv-Shaft with MIT License | 5 votes |
@Override void initData() { Observable<ListIllust> api = null; if (type == 1) { api = Retro.getAppApi().getUserLikeIllust(sUserModel.getResponse().getAccess_token(), mUserDetailResponse.getUser().getId(), FragmentLikeIllust.TYPE_PUBLUC); } else if (type == 2) { api = Retro.getAppApi().getUserSubmitIllust(sUserModel.getResponse().getAccess_token(), mUserDetailResponse.getUser().getId(), "illust"); } else if (type == 3) { api = Retro.getAppApi().getUserSubmitIllust(sUserModel.getResponse().getAccess_token(), mUserDetailResponse.getUser().getId(), "manga"); } if (api != null) { api.subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new NullCtrl<ListIllust>() { @Override public void success(ListIllust listIllust) { allItems.clear(); if (listIllust.getList().size() > 10) { allItems.addAll(listIllust.getList().subList(0, 10)); } else { allItems.addAll(listIllust.getList()); } mAdapter.notifyItemRangeInserted(0, allItems.size()); } @Override public void must(boolean isSuccess) { baseBind.progress.setVisibility(View.INVISIBLE); } }); } }
Example #30
Source File: MainActivity.java From SocialMentionAutoComplete with Apache License 2.0 | 5 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); observable = Observable.just("hello", "how ", "r ", "you"); single .subscribeOn(Schedulers.io()) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(stringSingleObserver); }