@Override public void showLoading() { Timber.tag(TAG).w("showLoading"); Observable.just(1) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Integer>() { @Override public void call(Integer integer) { } }); }
@Override public void loadData() { RetrofitHelper.getBiliGoAPI() .getNewBangumiSerialList() .compose(this.bindToLifecycle()) .doOnSubscribe(this::showProgressBar) .map(NewBangumiSerialInfo::getList) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listBeans -> { newBangumiSerials.addAll(listBeans); finishTask(); }, throwable -> { hideProgressBar(); }); }
private void search() { RxView.clicks(mSearchBtn) .throttleFirst(2, TimeUnit.SECONDS) .map(aVoid -> mSearchEdit.getText().toString().trim()) .filter(s -> !TextUtils.isEmpty(s)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(s -> { KeyBoardUtil.closeKeybord(mSearchEdit, TotalStationSearchActivity.this); showSearchAnim(); clearData(); content = s; getSearchData(); }); }
/** * 重写onTouchEvent, 当用户的手在MyScrollView上面的时候, * 直接将MyScrollView滑动的Y方向距离回调给onScroll方法中,当用户抬起手的时候, * MyScrollView可能还在滑动,所以当用户抬起手我们隔5毫秒给handler发送消息,在handler处理 * MyScrollView滑动的距离 */ @Override public boolean onTouchEvent(MotionEvent ev) { if(onScrollListener != null){ lastScrollX = this.getScrollX(); onScrollListener.onScroll(this.getScrollX()); } switch(ev.getAction()){ case MotionEvent.ACTION_UP: Observable.timer(500, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { if(onScrollListener != null){ onScrollListener.onScrollStop(); } } }); break; } return super.onTouchEvent(ev); }
@Override public void loadData() { RetrofitHelper.getBiliAppAPI() .getVideoDetails(av) .compose(this.bindToLifecycle()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(videoDetails -> { mVideoDetailsInfo = videoDetails.getData(); LogUtil.test(" VideoDetails finishTask" + mVideoDetailsInfo.getTitle()); finishTask(); }, throwable -> { mFAB.setClickable(false); mFAB.setBackgroundTintList(ColorStateList.valueOf( getResources().getColor(R.color.gray_20))); }); }
@Override public void getSearchResultList(String query) { Subscription rxSubscription = bookApi.getSearchResult(query).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<SearchDetail>() { @Override public void onNext(SearchDetail bean) { List<SearchDetail.SearchBooks> list = bean.books; if (list != null && !list.isEmpty() && mView != null) { mView.showSearchResultList(list); } } @Override public void onCompleted() { } @Override public void onError(Throwable e) { LogUtils.e(e.toString()); } }); addSubscrebe(rxSubscription); }
public static <T> Observable.Transformer<ApiResponse<T>, ApiResponse<T>> handleResult() { return new Observable.Transformer<ApiResponse<T>, ApiResponse<T>>() { @Override public Observable<ApiResponse<T>> call(Observable<ApiResponse<T>> tObservable) { return tObservable.flatMap(new Func1<ApiResponse<T>, Observable<ApiResponse<T>>>() { @Override public Observable<ApiResponse<T>> call(ApiResponse<T> response) { if (response.state.code == 0) { return createData(response); } else { return Observable.error(new ApiException(response.state)); } } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); } }; }
@Override protected void loadData() { Observable.just(readAssetsJson()) .compose(bindToLifecycle()) .map(s -> new Gson().fromJson(s, RegionTypesInfo.class)) .map(RegionTypesInfo::getData) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(dataBeans -> { regionTypes.addAll(dataBeans); finishTask(); }, throwable -> { }); }
/** * 获取验证码 */ public void getCode(HttpResultListener<Boolean> listener, final String tel) { mApi.getCode(tel) .map(new HttpResultFuncNoList()) .map(new Func1<String, Boolean>() { @Override public Boolean call(String s) { if (s.equals("ok")) { return true; } else { return false; } } }) .subscribeOn(Schedulers.io())//在工作线程请求网络 .observeOn(AndroidSchedulers.mainThread())//在主线程处理结果 .subscribe(new HttpResultSubscriber<>(listener)); }
public Observable<String> localData(){ return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { String data = getLocalData(); if(data!=null) { userId=data; println("local:"+Thread.currentThread()); subscriber.onNext(userId+" "+"source:local"); subscriber.onCompleted(); }else { subscriber.onCompleted(); } } }).observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()); }
@Override public void getBookReviewDetail(String id) { Subscription rxSubscription = bookApi.getBookReviewDetail(id).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<BookReview>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { LogUtils.e("getBookReviewDetail:" + e.toString()); } @Override public void onNext(BookReview data) { mView.showBookReviewDetail(data); } }); addSubscrebe(rxSubscription); }
@Override public void update(long read, long count, boolean done) { if(downInfo.getCountLength()>count){ read=downInfo.getCountLength()-count+read; }else{ downInfo.setCountLength(count); } downInfo.setReadLength(read); if (mSubscriberOnNextListener.get() != null) { /*接受进度消息,造成UI阻塞,如果不需要显示进度可去掉实现逻辑,减少压力*/ rx.Observable.just(read).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { /*如果暂停或者停止状态延迟,不需要继续发送回调,影响显示*/ if(downInfo.getState()==DownState.PAUSE||downInfo.getState()==DownState.STOP)return; downInfo.setState(DownState.DOWN); mSubscriberOnNextListener.get().updateProgress(aLong,downInfo.getCountLength()); } }); } }
/** * 删除包裹中商品申报信息 * * @param goodsId * @param inventoryId */ public void requestDelPackageGoods(int goodsId, int inventoryId) { mModel.deleteGoods(goodsId, inventoryId) .subscribeOn(Schedulers.io()) .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ErrorHandleSubscriber<BaseJson<String>>(mErrorHandler) { @Override public void onNext(BaseJson<String> listBaseJson) { if (listBaseJson.getStatus() == 0) { mRootView.showMessage("操作成功"); requestPackageDetail(mPackagesId); } else { mRootView.showMessage(listBaseJson.getMsgs()); } } }); }
public void setColor(@ColorInt Integer destinationColor){ if(isInEditMode()){ mPaint.setColor(destinationColor); this.invalidate(); return; } int currentColor = mPaint.getColor(); Integer[] intermediateColors = new Integer[10]; for(int i=1;i<=10;i++) intermediateColors[i-1] = UiUtils.blendColors(destinationColor,currentColor,0.1f*i); // Timer observable that will emit every half second. Observable<Long> timerObservable = Observable.interval(0, 20, TimeUnit.MILLISECONDS); Observable<Integer> colorsObservable = Observable.from(intermediateColors); // First, zip the timer and circle views observables, so that we get one circle view every half a second. Observable.zip(colorsObservable, timerObservable, (color, aLong) -> color) .observeOn(AndroidSchedulers.mainThread()) .subscribe(color -> { mPaint.setColor(color); this.invalidate(); }); }
private void loadSavedStories(final SavedStoriesCardAdapter savedStoriesCardAdapter, HackerNewsApiClient service) { savedStoriesCardAdapter.clear(); mSwipeRefreshLayout.setRefreshing(true); Observable.from(mDatabaseService.getItems().keySet()) .map(Integer::valueOf) .concatMapEager(id -> service.getItem(id)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Item>() { @Override public void onCompleted() { mSwipeRefreshLayout.setRefreshing(false); } @Override public void onError(Throwable e) { Log.e("NETWORKERROR", "Something went wrong" + e.getMessage(), e); } @Override public void onNext(Item item) { savedStoriesCardAdapter.addData(item); } }); }
public void getBookDetail(String bookId) { Subscription rxSubscription = bookApi.getBookDetail(bookId).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<BookDetail>() { @Override public void onNext(BookDetail data) { if (data != null && mView != null) { mView.showBookDetail(data); } } @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.e(TAG, "onError: " + e); } }); addSubscrebe(rxSubscription); }
@Override protected void initView() { swipeRefreshLayout.setColorSchemeResources(R.color.app_bar_bg_dark); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Observable.timer(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { swipeRefreshLayout.setRefreshing(false); } }); } }); }
private void getTopStories() { mSubscriptions.add(mDataManager.getTopStories() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(mDataManager.getScheduler()) .subscribe(new Subscriber<Post>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { hideLoadingViews(); Timber.e("There was a problem loading the top stories " + e); e.printStackTrace(); DialogFactory.createSimpleOkErrorDialog( getActivity(), getString(R.string.error_stories) ).show(); } @Override public void onNext(Post post) { hideLoadingViews(); mPostAdapter.addItem(post); } })); }
@Override public void loadData() { RetrofitHelper.getBiliAppAPI() .getVideoDetails(av) .compose(this.bindToLifecycle()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(videoDetails -> { mVideoDetailsInfo = videoDetails.getData(); finishTask(); }, throwable -> { mFAB.setClickable(false); mFAB.setBackgroundTintList(ColorStateList.valueOf( getResources().getColor(R.color.gray_20))); }); }
public void getUserInfo() { RetrofitHelper.getAccountAPI() .getUserInfoById(mid) .compose(this.bindToLifecycle()) .doOnSubscribe(this::showProgressBar) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(userInfo -> { mUserDetailsInfo = userInfo; finishTask(); }, throwable -> { hideProgressBar(); }); }
public static Observable<File> get(RequestManager requestManager, String url) { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { try { subscriber.onNext(requestManager.load(url) .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .get()); } catch (InterruptedException | ExecutionException e) { subscriber.onError(e); } finally { subscriber.onCompleted(); } } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }
@Override protected void loadData() { RetrofitHelper.getRankAPI() .getOriginalRanks(mOrder) .compose(bindToLifecycle()) .map(originalRankInfo -> originalRankInfo.getRank().getList()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(listBeans -> { mOriginalRanks.addAll(listBeans.subList(0, 20)); finishTask(); }, throwable -> { mSwipeRefreshLayout.setRefreshing(false); LogUtil.all(throwable.getMessage()); ToastUtil.shortToast("加载失败啦,请重新加载~"); }); }
private void postToken(String id, String token){ try { application.getWebService() .onlyToken(id, token) .retryWhen(new RetryWithDelay(3,2000)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new BaseSubscriber<SuccessResponse>() { @Override public void onNext(SuccessResponse response) { } }); } catch (Exception e) { e.printStackTrace(); } }
private void changeMyName() { showWaitingDialog(UIUtils.getString(R.string.please_wait)); String nickName = mEtName.getText().toString().trim(); ApiRetrofit.getInstance().setName(nickName) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(setNameResponse -> { hideWaitingDialog(); if (setNameResponse.getCode() == 200) { Friend friend = DBManager.getInstance().getFriendById(UserCache.getId()); if (friend != null) { friend.setName(nickName); friend.setDisplayName(nickName); DBManager.getInstance().saveOrUpdateFriend(friend); BroadcastManager.getInstance(ChangeMyNameActivity.this).sendBroadcast(AppConst.CHANGE_INFO_FOR_ME); BroadcastManager.getInstance(ChangeMyNameActivity.this).sendBroadcast(AppConst.CHANGE_INFO_FOR_CHANGE_NAME); } finish(); } }, this::loadError); }
private void scanBleDevices() { mScanSubscroption = mRxBleClient .scanBleDevices() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .filter(rxBleScanResult -> { return FilterDeviceName.equals(rxBleScanResult.getBleDevice().getName()); }) .subscribe(rxBleScanResult -> { int position = DeviceContext.AddorUpdateDevice(rxBleScanResult.getBleDevice() .getMacAddress(), rxBleScanResult.getRssi()); if (position >= 0) mScanDevices.getAdapter().notifyItemChanged(position); else mScanDevices.getAdapter().notifyDataSetChanged(); }, this::onScanFailure); }
private void unlockNextAccount(final String productId) { mSubscriptions.add( mBillingModel .purchase(productId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(new DefaultObserver<String>() { @Override public void onNext(String s) { super.onNext(s); if (TextUtils.equals(s, productId)) Snackbar.make(findViewById(R.id.coordinator), R.string.purchased, Snackbar.LENGTH_LONG).show(); } }) ); }
@Override public void getBookDisscussionDetail(String id) { Subscription rxSubscription = bookApi.getBookDisscussionDetail(id).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Disscussion>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { LogUtils.e("getBookDisscussionDetail:" + e.toString()); } @Override public void onNext(Disscussion disscussion) { mView.showBookDisscussionDetail(disscussion); } }); addSubscrebe(rxSubscription); }
/** * This is the core of the whole thing, since the response from the api must be a ResponseBody * in form of a continuous stream, I must extract the stream coming from the ResponseBody object * and map it into a source which is readable continuously. * The incoming stream separates objects from one another by returning lines separated by * \r\n and that's why it's necessary to truncate the stream and transform each line into a * Status java object which is in turn passed up to the subscriber. */ public Subscription getStatus(Subscriber<Status> subscriber, String track) { return ITwitterStreamingAPI.getStreamingStatuses(track, "low") .subscribeOn(Schedulers.io()) .flatMap(new Func1<ResponseBody, Observable<Status>>() { @Override public Observable<Status> call(ResponseBody responseBody) { return statuses(responseBody.source()); } }) .observeOn(AndroidSchedulers.mainThread()) .onErrorResumeNext(new Func1<Throwable, Observable<? extends Status>>() { @Override public Observable<? extends Status> call(Throwable throwable) { return Observable.error(throwable); } }) .subscribe(subscriber); }
private void submitSingleImage(String imageurl) throws Exception { application.getWebService() .insertImage(imageurl, MySharedPreferences.getUserId(preferences), MySharedPreferences.getUserToken(preferences)) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .retryWhen(new RetryWithDelay(3,2000)) .subscribe(new BaseSubscriber<SuccessResponse>() { @Override public void onNext(SuccessResponse response) { //Todo add network call for uploading profile_image file Toast.makeText(ChangeProfileActivity.this, "Successfully changed Profile Image", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { try { Timber.e(e.getMessage()); // Toast.makeText(ChangeProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); }catch (Exception ex){ ex.printStackTrace(); } } }); }
@Override public void getBookDisscussionComments(String disscussionId, int start, int limit) { Subscription rxSubscription = bookApi.getBookDisscussionComments(disscussionId, start + "", limit + "") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<CommentList>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { LogUtils.e("getBookDisscussionComments:" + e.toString()); } @Override public void onNext(CommentList list) { mView.showBookDisscussionComments(list); } }); addSubscrebe(rxSubscription); }
@Override public void getBookListDetail(String bookListId) { Subscription rxSubscription = bookApi.getBookListDetail(bookListId).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<BookListDetail>() { @Override public void onCompleted() { mView.complete(); } @Override public void onError(Throwable e) { LogUtils.e("getBookListDetail:" + e.toString()); mView.complete(); } @Override public void onNext(BookListDetail data) { mView.showBookListDetail(data); } }); addSubscrebe(rxSubscription); }
@Override public void loadData() { RetrofitHelper.getLiveAPI() .getLiveAppIndex() .compose(bindToLifecycle()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(liveAppIndexInfo -> { mLiveAppIndexAdapter.setLiveInfo(liveAppIndexInfo); finishTask(); }, throwable -> { }); }
public void getShopInfo() { checkViewAttached(); RxUtil.unsubscribe(mGetShopInfoSubscription); mGetShopInfoSubscription = mDataManager.getShopInfo().observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()).subscribe(new Subscriber<ShopInfoResponse>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(ShopInfoResponse shopInfoResponse) { getMvpView().showShopInfo(shopInfoResponse); } }); }
public void runCode() { Observable.create(new Observable.OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { subscriber.onNext(1); subscriber.onCompleted(); } }).subscribeOn(AndroidSchedulers.mainThread()) // 在doOnSubscribe()之前,不会影响上面的doOnSubscribe() .doOnRequest(new Action1<Long>() { @Override public void call(Long aLong) { println("doOnRequest:"+Thread.currentThread()); } }) .subscribeOn(Schedulers.io()) // 会影响上面的doOnSubscribe() .subscribe(new Observer<Integer>() { .observeOn(AndroidSchedulers.mainThread()) // 不会影响上面的doOnSubscribe() .subscribe(new Action1<Integer>() { @Override public void call(Integer integer) { println(Thread.currentThread().getName()); } }); }
@Override public void getBestComments(String disscussionId) { Subscription rxSubscription = bookApi.getBestComments(disscussionId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<CommentList>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { LogUtils.e("getBestComments:" + e.toString()); } @Override public void onNext(CommentList list) { mView.showBestComments(list); } }); addSubscrebe(rxSubscription); }
public void addFriend(String userId) { String msg = getView().getEtMsg().getText().toString().trim(); ApiRetrofit.getInstance().sendFriendInvitation(userId, msg) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(friendInvitationResponse -> { if (friendInvitationResponse.getCode() == 200) { UIUtils.showToast(UIUtils.getString(R.string.rquest_sent_success)); mContext.finish(); } else { UIUtils.showToast(UIUtils.getString(R.string.rquest_sent_fail)); } }, this::loadError); }
public static Observable<Boolean> refreshAlbum(final String key) { return Observable .create(new Observable.OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { refreshAlbumImp(key); subscriber.onNext(true); subscriber.onCompleted(); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()); }
private void showImportWarnDialog(final boolean skipFirstLine, final List<String> importColumns) { Runnable runnable = new Runnable() { @Override public void run() { showImportingDlg(); Observable.just(0) .observeOn(Schedulers.newThread()) .map(new Func1<Integer, Integer>() { @Override public Integer call(Integer name) { try { return ExportTool.importCsv(mTableName, mSelectedPath, skipFirstLine, importColumns); } catch (NoSuchFieldException e) { e.printStackTrace(); return Constant.FAIL; } } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Integer>() { @Override public void call(Integer result) { hideImportingDlg(); if (result == SqlConstant.SUCCESS) { ToastManger.showDoneToast(SqlTabDatasActivity.this, R.string.operation_success); getData(null, true, false, null, null); } else { ToastManger.showErrorToast(SqlTabDatasActivity.this, R.string.operation_failed); } } }); } }; FeViewUtils.createMsgDialog(SqlTabDatasActivity.this, R.string.column_count_not_same, R.string.cancel, R.string.okey, runnable); }
private void fetchAppUpdates() { subscriptions.add(appService.byPackageName(app.packageName()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(app -> { this.app = app; initView(app); }, throwable -> Timber.d(throwable, "while fetching apps"))); }
public void requestRegions(int type, int id) { mModel.getRegions(id) .subscribeOn(Schedulers.io()) .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔 .doOnSubscribe(new Action0() { @Override public void call() { } }).subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .doAfterTerminate(new Action0() { @Override public void call() { } }) .subscribe(new ErrorHandleSubscriber<BaseJson<List<Region>>>(mErrorHandler) { @Override public void onNext(BaseJson<List<Region>> orders) { mRegions.clear(); for (Region region : orders.getData()) { mRegions.add(region); } mRootView.setRegions(type, mRegions); } }); }