Java Code Examples for io.reactivex.schedulers.Schedulers

The following are top voted examples for showing how to use io.reactivex.schedulers.Schedulers. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: EazyBaseMVP   File: RxUtils.java   Source Code and License 6 votes vote down vote up
public static <T> FlowableTransformer<T, T> applySchedules(final IView view) {
    return new FlowableTransformer<T, T>() {
        @Override
        public Publisher<T> apply(Flowable<T> upstream) {
            return upstream.subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Subscription>() {
                        @Override
                        public void accept(Subscription subscription) throws Exception {
                            view.showLoading();
                        }
                    })
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnTerminate(new Action() {
                        @Override
                        public void run() throws Exception {
                            view.hideLoading();
                        }
                    });
        }
    };
}
 
Example 2
Project: REDAndroid   File: RequestPresenter.java   Source Code and License 6 votes vote down vote up
public void loadRequest(int id) {
    checkViewAttached();
    getMvpView().showLoadingProgress(true);

    mSubscription.add(mDataManager.getRequest(id)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribeWith(new DisposableSingleObserver<Request>() {
                @Override
                public void onSuccess(Request request) {
                    getMvpView().showRequest(request);
                    getMvpView().showLoadingProgress(false);
                }

                @Override
                public void onError(Throwable error) {
                    getMvpView().showError(error.getMessage());
                    getMvpView().showLoadingProgress(false);
                }
            }));
}
 
Example 3
Project: NewAndroidArchitecture   File: CountriesViewModel.java   Source Code and License 6 votes vote down vote up
@MainThread
@NonNull
LiveData<Response<List<Country>>> getMoviesList() {
    if (countriesLiveData == null) {
        countriesLiveData = new MutableLiveData<>();
        countriesRepository.getCountries()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> loadingLiveData.setValue(true))
                .doAfterTerminate(() -> loadingLiveData.setValue(false))
                .subscribe(
                        countries1 -> countriesLiveData.setValue(Response.success(countries1)),
                        throwable -> countriesLiveData.setValue(Response.error(throwable))
                );
    }
    return countriesLiveData;
}
 
Example 4
Project: FCM-for-Mojo   File: ServerSettingsFragment.java   Source Code and License 6 votes vote down vote up
private void restart() {
    mCompositeDisposable.add(FFMService.restart()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doFinally(new Action() {
                @Override
                public void run() throws Exception {
                    findPreference("restart_webqq").setEnabled(true);
                }
            })
            .subscribe(new Consumer<FFMResult>() {
                @Override
                public void accept(FFMResult ffmResult) throws Exception {
                    Toast.makeText(getContext(), "Succeed.", Toast.LENGTH_SHORT).show();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Toast.makeText(getContext(), "Network error:\n" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }));
}
 
Example 5
Project: rookit-core   File: ImportAction.java   Source Code and License 6 votes vote down vote up
private void choose(TrackPath source, SingleTrackAlbumBuilder result) {
	final Single<Boolean> dbOp = Single.fromCallable(() -> {
		new TrackPathNormalizer(source).removeTags();
		db.addAlbum(result.build());
		updateHits(result);
		return true;
	}).observeOn(Schedulers.io());

	Single.fromCallable(() -> {
		return askForRemoval(source);
	}).zipWith(dbOp, (one, another) -> one && another)
	.subscribe(toDelete -> {
		if(toDelete) {
			Files.delete(source.getPath());
		}
	});
}
 
Example 6
Project: mvvm-template   File: EmojiManager.java   Source Code and License 6 votes vote down vote up
public static void load() {
    RxHelper.safeObservable(Observable.fromCallable(() -> {
        try {
            InputStream stream = App.getInstance().getAssets().open(PATH);
            List<Emoji> emojis = EmojiLoader.loadEmojis(stream);
            ALL_EMOJIS = emojis;
            for (Emoji emoji : emojis) {
                for (String tag : emoji.getTags()) {
                    if (EMOJIS_BY_TAG.get(tag) == null) {
                        EMOJIS_BY_TAG.put(tag, new HashSet<>());
                    }
                    EMOJIS_BY_TAG.get(tag).add(emoji);
                }
                for (String alias : emoji.getAliases()) {
                    EMOJIS_BY_ALIAS.put(alias, emoji);
                }
            }
            EMOJI_TRIE = new EmojiTrie(emojis);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    })).subscribeOn(Schedulers.io()).subscribe();
}
 
Example 7
Project: MyEyepetizer   File: SearchActivity.java   Source Code and License 6 votes vote down vote up
private void searchData(String tag) {
    mHintText.setText("");
    mTagLayout.setVisibility(View.GONE);
    mProgressBar.setVisibility(View.VISIBLE);
    mSearchTag = tag;
    Observable<GetDataBean> observable = mSearchApi.searchTagData(mSearchTag);
    observable
            .filter(new Predicate<GetDataBean>() {
                @Override
                public boolean test(@NonNull GetDataBean getDataBean) throws Exception {
                    return getDataBean != null;
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(mObserver);
}
 
Example 8
Project: android-permission-checker-app   File: PermissionGroupPresenterImpl.java   Source Code and License 6 votes vote down vote up
private void fetchData() {
  getView().showProgressBar();
  getView().hideListView();
  getCompositeDisposable().add(getDataProvider().getPermissionGroups(false)
      .subscribeOn(Schedulers.computation())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new DisposableSingleObserver<ArrayList<PermissionGroupDetails>>() {
        @Override
        public void onSuccess(ArrayList<PermissionGroupDetails> permissionGroupDetails) {
          getView().hideProgressBar();
          getView().showListView();
          permissionList = permissionGroupDetails;
          getView().notifyListAdapter();
        }

        @Override public void onError(Throwable e) {

        }
      }));
}
 
Example 9
Project: NodeET   File: UserProfileActivity.java   Source Code and License 6 votes vote down vote up
private void getUserProfile() {
    mUserService.me()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(u -> {
                        mUserName.setText(u.getUsername());
                        mAvatarView.setAvatarOfUser(u);
                        mReputation.setText(u.getReputation());
                        mPost.setText(u.getPostcount());
                        mFollowing.setText(String.valueOf(u.getFollowingCount()));
                        mFollower.setText(String.valueOf(u.getFollowerCount()));
                        mLoginTime.setText(DateTimeFormatter.format(Long.parseLong(u.getLastonline())));
                        mRegTime.setText(DateTimeFormatter.format(Long.parseLong(u.getJoindate())));
                        mProfileViews.setText(u.getProfileviews());
                        mEmail.setText(u.getEmail());
                        GlideApp.with(UserProfileActivity.this)
                                .load(NodeBBService.url(u.getCoverUrl()))
                                .into(new SimpleTarget<Drawable>() {
                                    @Override
                                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                                        mHeaderView.setBackground(resource);
                                    }
                                });
                    });
}
 
Example 10
Project: REDAndroid   File: LoginPresenter.java   Source Code and License 6 votes vote down vote up
public void login(String username, String password) {
    checkViewAttached();
    getMvpView().showLoadingProgress(true);

    mSubscription.add(mDataManager.login(username, password, 1)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribeWith(new DisposableSingleObserver<Boolean>() {
                @Override
                public void onSuccess(Boolean success) {
                    if (success) {
                        loginWithCookie();
                    } else {
                        getMvpView().showError("Login Failed");
                    }
                }

                @Override
                public void onError(Throwable error) {
                    getMvpView().showError(error.getMessage());
                    getMvpView().showLoadingProgress(false);
                }
            }));
}
 
Example 11
Project: REDAndroid   File: DataManager.java   Source Code and License 6 votes vote down vote up
public Single<Boolean> login(String username, String password, int stayLoggedIn) {
    return mApiService.login(username, password, stayLoggedIn)
            .subscribeOn(Schedulers.io())
            .flatMap(new Function<Response<ResponseBody>, Single<? extends Boolean>>() {
                @Override public Single<? extends Boolean> apply(
                    Response<ResponseBody> responseBodyResponse) {
                    String header = responseBodyResponse.raw().header("Set-Cookie", "");
                    if (header.contains("session")
                        && !header.contains("deleted")
                        && !header.contains("redirect")) {
                        return Single.just(true);
                    } else {
                        getPreferencesHelper().clearCookies();
                        return Single.just(false);
                    }
                }
            });
}
 
Example 12
Project: clustercode   File: TranscodingServiceImpl.java   Source Code and License 6 votes vote down vote up
@Inject
TranscodingServiceImpl(ExternalProcessService externalProcessService,
                       TranscoderSettings transcoderSettings,
                       MediaScanSettings mediaScanSettings,
                       OutputParser parser) {
    this.externalProcessService = externalProcessService;
    this.transcoderSettings = transcoderSettings;
    this.mediaScanSettings = mediaScanSettings;

    this.parser = parser;

    this.publisher = PublishSubject.create().toSerialized();

    publisher.ofType(TranscodeTask.class)
             .skipWhile(o -> isActive())
             .observeOn(Schedulers.computation())
             .subscribeOn(Schedulers.io())
             .subscribe(this::prepareTranscode);
}
 
Example 13
Project: NovelReader   File: BookListPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void loadBookList(BookListType type, String tag, int start, int limited) {
    Disposable refreshDispo = getBookListSingle(type, tag, start, limited)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    (beans)-> {
                        mView.finishLoading(beans);
                    }
                    ,
                    (e) ->{
                        mView.showLoadError();
                        LogUtils.e(e);
                    }
            );
    addDisposable(refreshDispo);
}
 
Example 14
Project: buckaroo   File: CommonTasks.java   Source Code and License 6 votes vote down vote up
public static Single<WriteFileEvent> writeFile(final String content, final Path path, final boolean overwrite) {
    Preconditions.checkNotNull(content);
    Preconditions.checkNotNull(path);
    return Single.fromCallable(() -> {
        if (path.getParent() != null && !Files.exists(path.getParent())) {
            Files.createDirectories(path.getParent());
        }
        if (overwrite) {
            Files.deleteIfExists(path);
        } else if (Files.isDirectory(path)) {
            throw new IOException("There is already a directory at " + path);
        } else if (Files.exists(path)) {
            throw new IOException("There is already a file at " + path);
        }
        final ByteSink sink = MoreFiles.asByteSink(path);
        sink.write(content.getBytes());
        return WriteFileEvent.of(path);
    }).subscribeOn(Schedulers.io());
}
 
Example 15
Project: Protein   File: ShotLikeListPresenter.java   Source Code and License 6 votes vote down vote up
@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 16
Project: DeepImagePreview-Project   File: ScanPresenter.java   Source Code and License 6 votes vote down vote up
private void registerMainThreadEvents() {
    Disposable disposable = RxBus.getInstance()
            .toObservable()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object o) throws Exception {

                    if (o instanceof OcrStatusChangedEvent) {

                        mScanView.handleOrcStatusChangedEvent(((OcrStatusChangedEvent) o));
                    } else if (o instanceof NewDetectionFoundEvent) {

                        mScanView.handleNewDetectionFound(((NewDetectionFoundEvent) o).getDetection());
                    } else if (o instanceof SearchResultReadyEvent) {

                        SearchResultReadyEvent event = (SearchResultReadyEvent) o;
                        mScanView.showPreviewResults(event.getSearchResultContainer(), event.getQuery());
                    }
                }
            });
    mCompositeDisposable.add(disposable);
}
 
Example 17
Project: LocationAware   File: LocationAlarmPresenter.java   Source Code and License 6 votes vote down vote up
private void addCheckPointMarkers() {
  getCheckPointDataSource().getAllCheckPoints()
      .toObservable()
      .doOnNext(checkPoints -> allCheckPoints = (ArrayList<CheckPoint>) checkPoints)
      .flatMap(Observable::fromIterable)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new DisposableObserver<CheckPoint>() {
        @Override public void onNext(CheckPoint checkPoint) {
          getView().addMarkerOnMap(checkPoint);
        }

        @Override public void onError(Throwable e) {
          getView().showError(e.getLocalizedMessage());
        }

        @Override public void onComplete() {
          getView().notifyListAdapter();
        }
      });
}
 
Example 18
Project: NeteaseCloudMusic   File: ConfigPresenter.java   Source Code and License 6 votes vote down vote up
public void requestLoadingList() {
    Observable.create(new ObservableOnSubscribe<List<ConfigBean>>() {
        @Override
        public void subscribe(ObservableEmitter<List<ConfigBean>> e) throws Exception {
            mModel = ConfigModel.getInstance(configView.getContext());
            e.onNext(mModel.getConfigList());
            mModel.setConfigCallback(ConfigPresenter.this);
        }
    })
            .observeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<ConfigBean>>() {
                @Override
                public void accept(List<ConfigBean> list) throws Exception {
                    configView.displayConfigList(list);
                }
            });

}
 
Example 19
Project: Ghost-Android   File: AuthService.java   Source Code and License 6 votes vote down vote up
public void refreshToken(AuthToken token) {
    if (mbRequestOngoing) {
        return;
    }
    mbRequestOngoing = true;
    mApi.getConfiguration()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
            .map(ConfigurationList::getClientSecret)
            .map(clientSecret -> new RefreshReqBody(token.getRefreshToken(), clientSecret))
            .flatMap(mApi::refreshAuthToken)
            // since this token was just refreshed, it doesn't have a refresh token, so add that
            .doOnNext(authToken -> authToken.setRefreshToken(token.getRefreshToken()))
                .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::handleAuthToken, this::handleRefreshError);
}
 
Example 20
Project: NovelReader   File: DiscReviewPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void refreshBookReview(BookSort sort, BookType bookType,
                              int start, int limited, BookDistillate distillate) {
    Disposable refreshDispo = RemoteRepository.getInstance()
            .getBookReviews(sort.getNetName(), bookType.getNetName(),
                    start, limited, distillate.getNetName())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    (beans)-> {
                        isLocalLoad = false;
                        mView.finishRefresh(beans);
                        mView.complete();
                    }
                    ,
                    (e) ->{
                        mView.complete();
                        mView.showErrorTip();
                        e(e);
                    }
            );
    addDisposable(refreshDispo);
}
 
Example 21
Project: IOTAFaucet   File: Frontend.java   Source Code and License 6 votes vote down vote up
public WorkWebsocket(Backend backend) {
    backend.getWorkObservable(workResponses).subscribe((req) -> {
        String msg = GSON.toJson(req);
        int offset = 0;
        for (Session session : sessions) {
            final int finalOffset = ++offset;
            Schedulers.io().scheduleDirect(()-> {
                try {
                    JsonObject finalMsg = GSON.fromJson(msg, JsonObject.class);
                    finalMsg.addProperty("offset", finalOffset);
                    session.getRemote().sendString(GSON.toJson(finalMsg));
                    System.out.println("Send message to a session");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    });

}
 
Example 22
Project: wayf-cloud   File: WayfRequestHandlerFactory.java   Source Code and License 6 votes vote down vote up
public void handle(RoutingContext event) {
    LOG.debug("Received request on URI [{}]", event.request().absoluteURI());

    RequestContextAccessor.set(requestContextFactory.fromRoutingContext(event));
    authenticate();

    Single.just(event)
            .observeOn(Schedulers.io())
            .flatMap((s_event) -> singleDelegate.apply(s_event))
            .subscribeOn(Schedulers.io()) // Write HTTP response on IO thread
            .subscribe(
                    (result) -> responseWriter.buildSuccess(event, result),
                    (e) -> event.fail(e)
            );

    RequestContextAccessor.remove();
}
 
Example 23
Project: richeditor   File: UploadHelper.java   Source Code and License 6 votes vote down vote up
public static Flowable<BaseUploadBean> generateFlowable(@NonNull RequestBodyWrapper uploadBeanEmitter, final String filePath){
    Flowable<BaseUploadBean> flowable = uploadBeanEmitter.getUploadProcessor()
            .publish()
            .autoConnect();

     return  flowable
             .filter(new Predicate<BaseUploadBean>() {
                 long oldProgress = 0;
                 @Override
                 public boolean test(BaseUploadBean baseUploadBean) throws Exception {
                     if(baseUploadBean instanceof UploadInfoBean){
                         long progress = ((UploadInfoBean) baseUploadBean).getData().getWrittenBytes();
                         if(progress - oldProgress > MIN_GRAD) {
                             oldProgress = progress;
                             return true;
                         }
                         return false;
                     }
                     oldProgress = 0;
                     return true;
                 }
             })
            //.throttleLast(100, TimeUnit.MILLISECONDS).mergeWith(flowable.takeLast(1))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example 24
Project: screen-share-to-browser   File: ServerService.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    Disposable disposable =
            RxBus.getDefault()
                    .toObservable(String.class)
                    .subscribeOn(Schedulers.io())
                    .doOnNext(new Consumer<String>() {
                        @Override
                        public void accept(String s) throws Exception {
                            wsServer.broadcast(s);
                        }
                    })
                    .subscribe();
    compositeDisposable.add(disposable);

    mAssetManager = getAssets();
}
 
Example 25
Project: DeepImagePreview-Project   File: MenuApplication.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    Picasso picasso = new Picasso.Builder(this)
            .loggingEnabled(BuildConfig.DEBUG)
            .indicatorsEnabled(false)
            .build();
    Picasso.setSingletonInstance(picasso);


    RxBus.getInstance()
            .toObservable()
            .subscribeOn(Schedulers.newThread())
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object o) throws Exception {
                    Log.d("EVENT", "onNewEvent: " + o.getClass().getSimpleName() + " [" + o.toString() + "]");
                }
            });
}
 
Example 26
Project: AssistantBySDK   File: StartUpActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 初始化区号
 **/
private void initZipCode() {
    Observable.create(new ObservableOnSubscribe<Object>() {
        @Override
        public void subscribe(ObservableEmitter<Object> e) throws Exception {
            Set<Map.Entry<String, String>> entries = ZipCodeMap.MAP.entrySet();
            List<Zipcode> zipCodeList = new ArrayList<>();
            for (Map.Entry<String, String> entry : entries) {
                Zipcode zipCode = new Zipcode();
                zipCode.setCity(entry.getKey());
                zipCode.setCode(entry.getValue());
                zipCodeList.add(zipCode);
            }
            CallAndSmsDao.getInstance(StartUpActivity.this).insertZipCodes(zipCodeList);
        }
    })
            .delay(1500, TimeUnit.MILLISECONDS)
            .observeOn(Schedulers.io())
            .subscribeOn(Schedulers.io())
            .subscribe();
}
 
Example 27
Project: RetroMusicPlayer   File: LyricsActivity.java   Source Code and License 6 votes vote down vote up
private void callAgain(final String title, final String artist) {
    mDisposable.clear();
    mDisposable.add(loadLyrics.downloadLrcFile(title, artist, MusicPlayerRemote.getSongDurationMillis())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .doOnSubscribe(disposable -> {
                mRefresh.startAnimation(rotateAnimation);
            })
            .subscribe(this::showLyricsLocal,
                    throwable -> {
                        mRefresh.clearAnimation();
                        showLyricsLocal(null);
                        loadLyricsWIki(title, artist);
                        hideLyrics(View.GONE);
                    }, () -> {
                        mRefresh.clearAnimation();
                        Toast.makeText(this, "Lyrics downloaded", Toast.LENGTH_SHORT).show();
                    }));
}
 
Example 28
Project: RxBroadcastReceiver   File: RxBroadcastReceiverTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldReturnErrorWhenSubscribeOnNonLooperThread() {
    //GIVEN
    final Observable<Intent> observable = RxBroadcastReceivers.fromIntentFilter(application, testIntentFilter)
            .subscribeOn(Schedulers.newThread());

    //WHEN
    final TestObserver<Intent> observer = observable.test();

    //THEN
    observer.awaitTerminalEvent();
    observer.assertTerminated();
}
 
Example 29
Project: Auto.js   File: BuildActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    String packageName = data.getStringExtra(ShortcutIconSelectActivity.EXTRA_PACKAGE_NAME);
    if (packageName != null) {
        try {
            mIcon.setImageDrawable(getPackageManager().getApplicationIcon(packageName));
            mIsDefaultIcon = false;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return;
    }
    if (data.getData() == null)
        return;
    Observable.fromCallable(() -> BitmapFactory.decodeStream(getContentResolver().openInputStream(data.getData())))
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((bitmap -> {
                mIcon.setImageBitmap(bitmap);
                mIsDefaultIcon = false;
            }), error -> {
                Log.e(LOG_TAG, "decode stream", error);
            });

}
 
Example 30
Project: EditPhoto   File: SaturationFragment.java   Source Code and License 5 votes vote down vote up
private void showImage() {
    Observable.just(inputUrl)
            .map(new Function<String, Bitmap>() {
                @Override
                public Bitmap apply(String url) throws Exception {
                    return getBitmap(url);
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Bitmap>() {
                @Override
                public void onSubscribe(Disposable d) {
                    showLoading();
                }

                @Override
                public void onNext(Bitmap bitmap) {
                    saturationView.setImageBitmap(bitmap);
                }

                @Override
                public void onError(Throwable e) {
                }

                @Override
                public void onComplete() {
                    hideLoading();
                }
            });
}
 
Example 31
Project: ZhaZhaShop   File: MovieDetailManager.java   Source Code and License 5 votes vote down vote up
/**
 * 获取相关资讯
 *
 * @param movieId
 * @return
 */
Observable<MovieRelatedInformationBean> getMovieRelatedInformation(int movieId) {
    return RetrofitClient.getInstance()
            .apiMovieDetailService()
            .getMovieRelatedInformation(movieId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example 32
Project: filestack-java   File: Upload.java   Source Code and License 5 votes vote down vote up
/**
 * Start this upload asynchronously. Returns progress updates.
 *
 * @return {@link Flowable} that emits {@link Progress} events
 */
public Flowable<Progress<FileLink>> run() {
  Flowable<Prog<FileLink>> startFlow = Flowable
      .fromCallable(new UploadStartFunc(this))
      .subscribeOn(Schedulers.io());

  // Create multiple func instances to each upload a subrange of parts from the file
  // Merge each of these together into one so they're executed concurrently
  Flowable<Prog<FileLink>> transferFlow = Flowable.empty();
  for (int i = 0; i < CONCURRENCY; i++) {
    UploadTransferFunc func = new UploadTransferFunc(this);
    Flowable<Prog<FileLink>> temp = Flowable
        .create(func, BackpressureStrategy.BUFFER)
        .subscribeOn(Schedulers.io());
    transferFlow = transferFlow.mergeWith(temp);
  }

  Flowable<Prog<FileLink>> completeFlow = Flowable
      .fromCallable(new UploadCompleteFunc(this))
      .subscribeOn(Schedulers.io());

  return startFlow
      .concatWith(transferFlow)
      .concatWith(completeFlow)
      .buffer(PROG_INTERVAL_SEC, TimeUnit.SECONDS)
      .flatMap(new ProgMapFunc(this));
}
 
Example 33
Project: NeteaseCloudMusic   File: FileUtil.java   Source Code and License 5 votes vote down vote up
public static void deleteFileOnDisk(Iterable<MusicBean> list) {
    Flowable.fromIterable(list).flatMap(new Function<MusicBean, Publisher<File>>() {
        @Override
        public Publisher<File> apply(MusicBean bean) throws Exception {
            return Flowable.just(new File(bean.getPath()));
        }
    }).observeOn(Schedulers.io())
            .subscribeOn(Schedulers.io())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(Integer.MAX_VALUE);
                }

                @Override
                public void onNext(File file) {
                    file.delete();
                }

                @Override
                public void onError(Throwable t) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example 34
Project: Android-Code-Demos   File: DiskCacheObservable.java   Source Code and License 5 votes vote down vote up
@Override
public void putDataToCache(final Image image) {

    Observable.create(new ObservableOnSubscribe<Image>() {
        @Override
        public void subscribe(ObservableEmitter<Image> e) throws Exception {
            putDataToDiskLruCache(image);
        }
    }).subscribeOn(Schedulers.io()).subscribe();


}
 
Example 35
Project: Mix   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void initDemoRX02() {
        Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                Log.e(TAG, "Observable thread is : " + Thread.currentThread().getName());
                Log.e(TAG, "emit 1");
                emitter.onNext(1);
            }
        });

        Consumer<Integer> consumer = new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                Log.e(TAG, "Observer thread is :" + Thread.currentThread().getName());
                Log.e(TAG, "onNext: " + integer);
            }
        };

//        observable.subscribe(consumer);

        /*
        * 多次指定上游的线程只有第一次指定的有效, 也就是说多次调用subscribeOn() 只有第一次的有效.
          多次指定下游的线程是可以的, 也就是说每调用一次observeOn() , 下游的线程就会切换一次.
        * */
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(consumer);
    }
 
Example 36
Project: Mvvm   File: MvvmViewModel.java   Source Code and License 5 votes vote down vote up
@Override
public final <T> void addSubscribe(io.reactivex.Observable<T> observable, Observer<T> observer) {
    if (null == observable || null == observer) {
        return;
    }
    observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer);
}
 
Example 37
Project: ZhaZhaShop   File: MovieDetailManager.java   Source Code and License 5 votes vote down vote up
/**
 * 获取长评数据
 *
 * @param movieId
 * @return
 */
Observable<MovieLongCommentBean> getMovieLongComment(int movieId) {
    return RetrofitClient.getInstance()
            .apiMovieDetailService()
            .getMovieLongComment(movieId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example 38
Project: Learning-RxJava   File: Ch8_13.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Flowable.interval(1, TimeUnit.MILLISECONDS)
            .onBackpressureBuffer(10,
                    () -> System.out.println("overflow!"),
                    BackpressureOverflowStrategy.DROP_LATEST)
            .observeOn(Schedulers.io())
            .subscribe(i -> {
                sleep(5);
                System.out.println(i);
            });
    sleep(5000);
}
 
Example 39
Project: AssistantBySDK   File: AlarmRingPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void stopRing() {
    if (isDelay) {
        /*mAlarm.setRtime(new SimpleDate().toValue() + 5);
        mAssistDao.updateAlarm(mAlarm);
        //开启闹钟服务
        Intent rIntent = new Intent(mContext, RemindService.class);
        rIntent.putExtra(RemindService.CMD, (RemindService.ALARM << 4) + RemindService.ADD);
        rIntent.putExtra(RemindService.ID, mAlarm.getId());
        mContext.startService(rIntent);*/
        Intent delayIntent = new Intent(mContext, AssistantService.class);
        delayIntent.putExtra(AssistantService.CMD, AssistantService.ServiceCmd.DELAY_ALARM);
        delayIntent.putExtra(RemindService.ID, mAlarm.getId());
        mContext.startService(delayIntent);

        //合成提示语音
        StringBuilder builder = new StringBuilder();
        SimpleDate sd = new SimpleDate();
        sd.setValue(sd.toValue() + 5);
        builder.append(sd.toString())
                .append("将再次响铃");
        SynthesizerBase.get().startSpeakAbsolute(builder.toString())
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .subscribe();
    } else if (mAlarm.getFrequency() == 0) {
        mAlarm.setValid(0);
        mAssistDao.updateAlarm(mAlarm);

    }
    player.stop();
    player.release();
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}
 
Example 40
Project: Learning-RxJava   File: Ch8_8.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Observable<Integer> source = Observable.create(emitter -> {
        for (int i = 0; i <= 1000; i++) {
            if (emitter.isDisposed())
                return;
            emitter.onNext(i);
        }
        emitter.onComplete();
    });
    source.observeOn(Schedulers.io())
            .subscribe(System.out::println);
    sleep(1000);
}
 
Example 41
Project: RxJava2-Android-Sample   File: TimeoutExampleActivity.java   Source Code and License 5 votes vote down vote up
private void testTimeoutWithObservable(){
    getObservable()
            .delay(1, TimeUnit.SECONDS)
            .timeout(200, TimeUnit.MILLISECONDS, Observable.just("10", "20"))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(getObserver());
}
 
Example 42
Project: Learning-RxJava   File: Ch8_15.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Flowable.interval(1, TimeUnit.MILLISECONDS)
            .onBackpressureDrop(i ->
                    System.out.println("Dropping " + i))
            .observeOn(Schedulers.io())
            .subscribe(i -> {
                sleep(5);
                System.out.println(i);
            });
    sleep(5000);
}
 
Example 43
Project: KTools   File: BaseApi.java   Source Code and License 5 votes vote down vote up
protected Service createProxyService(final Service service) {
    Class<Service> serviceClass = getServiceClass();
    return (Service) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (NetworkUtils.isNetAvailable()) {
                return ((Flowable) method.invoke(service, args)).subscribeOn(Schedulers.io());
            } else {
                return Flowable.error(new NetworkErrorException()).subscribeOn(Schedulers.io());
            }
        }
    });
}
 
Example 44
Project: MyEyepetizer   File: FollowFragment.java   Source Code and License 5 votes vote down vote up
private void loadDataByNet() {
    mFollowApi = RetrofitFactory.getRetrofit().createApi(FollowApi.class);
    Observable<GetDataBean> observable = mFollowApi.getFollowData();
    mIsLoading = true;
    observable
            .filter(new Predicate<GetDataBean>() {
                @Override
                public boolean test(@NonNull GetDataBean getDataBean) throws Exception {
                    return getDataBean != null;
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(mObserver);
}
 
Example 45
Project: Quran   File: CoordinatesModel.java   Source Code and License 5 votes vote down vote up
public Observable<Pair<Integer, RectF>> getPageCoordinates(Integer... pages) {
  AyahInfoDatabaseHandler database = ayahInfoDatabaseProvider.getAyahInfoHandler();
  if (database == null) {
    return Observable.error(new NoSuchElementException("No AyahInfoDatabaseHandler found!"));
  }

  return Observable.fromArray(pages)
      .map(page -> new Pair<>(page, database.getPageBounds(page)))
      .subscribeOn(Schedulers.computation());
}
 
Example 46
Project: RxJava2-Android-Sample   File: ZipExampleActivity.java   Source Code and License 5 votes vote down vote up
private void doSomeWork() {
    Observable.zip(getCricketFansObservable(), getFootballFansObservable(),
            new BiFunction<List<User>, List<User>, List<User>>() {
                @Override
                public List<User> apply(List<User> cricketFans, List<User> footballFans) throws Exception {
                    return Utils.filterUserWhoLovesBoth(cricketFans, footballFans);
                }
            })
            // Run on a background thread
            .subscribeOn(Schedulers.io())
            // Be notified on the main thread
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(getObserver());
}
 
Example 47
Project: Reactive-Android-Programming   File: Sandbox.java   Source Code and License 5 votes vote down vote up
private static void demo3() {
    final ExecutorService executor = Executors.newFixedThreadPool(10);
    final Scheduler pooledScheduler = Schedulers.from(executor);

    Observable.range(1, 100)
            .subscribeOn(pooledScheduler)
            .map(Objects::toString)
            .subscribe(e -> log("subscribe", e));
}
 
Example 48
Project: simple-stack   File: SchedulerModule.java   Source Code and License 5 votes vote down vote up
@Provides
@Named("WRITE_SCHEDULER")
@Singleton
SchedulerHolder writeScheduler(SchedulerHolder schedulerHolder) {
    schedulerHolder.setScheduler(Schedulers.from(Executors.newSingleThreadExecutor()));
    return schedulerHolder;
}
 
Example 49
Project: dztools   File: NTPSynchTask.java   Source Code and License 5 votes vote down vote up
public Observable<Long> get() {
    return Observable
        .interval(0L,
                  pluginConfig.ntpSynchInterval(),
                  TimeUnit.MILLISECONDS,
                  Schedulers.io())
        .doOnNext(counter -> logger.debug("Starting NTP synch task..."))
        .flatMapSingle(counter -> ntpFetch.get())
        .doOnNext(ntp -> logger.debug("Received new NTP " + DateTimeUtil.formatMillis(ntp)))
        .doOnError(e -> logger.error("NTP synch failed! " + e.getMessage()));
}
 
Example 50
Project: ZhaZhaShop   File: MovieStarManager.java   Source Code and License 5 votes vote down vote up
public Observable<MovieStarHonor> getMovieStarHonor(int starId) {
    return RetrofitClient.getInstance()
            .apiMovieStarService()
            .getMovieStarHonors(starId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example 51
Project: Renrentou   File: XApi.java   Source Code and License 5 votes vote down vote up
/**
 * 线程切换
 *
 * @return
 */
public static <T extends IModel> FlowableTransformer<T, T> getScheduler() {
    return new FlowableTransformer<T, T>() {
        @Override
        public Publisher<T> apply(Flowable<T> upstream) {
            return upstream.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    };
}
 
Example 52
Project: hellomvp   File: MoviePresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void getTopMovie(int start, int count) {
    mView.startLoading();
    mMovieModel.getTopMovie(start, count)
            .subscribeOn(Schedulers.io())//请求发生在io线程
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<MovieEntity>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(MovieEntity movieEntity) {
                    mView.showData(movieEntity);
                }

                @Override
                public void onError(Throwable e) {
                    mView.error(e);
                }

                @Override
                public void onComplete() {
                    mView.complete();
                }
            });

}
 
Example 53
Project: RxGooglePhotos   File: GooglePhotosService.java   Source Code and License 5 votes vote down vote up
/**
 * Get user feed, feed contains all user various albums and photos collection.
 *
 * @param startIndex start album index (first index is 1)
 * @param maxResults max results
 * @return {@link UserFeed} object.
 */
public Single<UserFeed> getUserFeed(int startIndex, int maxResults) {
    if (startIndex < 1) {
        throw new IllegalArgumentException("Illegal start index, must be above 0");
    }
    return picasaApi.getUserFeedResponse(startIndex, maxResults)
            .map(UserFeedResponse::getFeed)
            .subscribeOn(Schedulers.io());
}
 
Example 54
Project: JRAW-Android-Sample   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
        Credentials credentials = ((MyApplication) getApplication())
                .getInstalledAppCredentials();

        disposables.add(RedditService.userAuthentication(
                    AuthenticationManager.get().getRedditClient(),
                    credentials,
                    data.getStringExtra("RESULT_URL"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableCompletableObserver() {
                    @Override
                    public void onComplete() {
                        String username = AuthenticationManager.get().getRedditClient()
                                .getAuthenticatedUser();
                        Toast.makeText(MainActivity.this, "Logged in as " + username,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, "Something went wrong",
                                Toast.LENGTH_SHORT).show();
                    }
                })
        );
    }
}
 
Example 55
Project: XSnow   File: ApiTransformer.java   Source Code and License 5 votes vote down vote up
public static <T> ObservableTransformer<T, T> norTransformer() {
    return new ObservableTransformer<T, T>() {
        @Override
        public ObservableSource<T> apply(Observable<T> apiResultObservable) {
            return apiResultObservable
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .retryWhen(new ApiRetryFunc(HttpGlobalConfig.getInstance().getRetryCount(),
                            HttpGlobalConfig.getInstance().getRetryDelayMillis()));
        }
    };
}
 
Example 56
Project: GifEmoji   File: EmoticonDrawable.java   Source Code and License 5 votes vote down vote up
void animation() {
    if (delay > 0 && frameNum > 0)
        Observable
                .interval(delay, TimeUnit.MILLISECONDS)
                .flatMap(new Function<Long, ObservableSource<Long>>() {
                    @Override
                    public ObservableSource<Long> apply(Long aLong) throws Exception {
                        return Observable.just(aLong);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long drawable) {
                        position++;
                        if (position >= frameNum) position = 0;
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
}
 
Example 57
Project: RetroMusicPlayer   File: AbsPlaylistAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public void onBindViewHolder(FullMetalViewHolder holder, int position) {
    // don't forget about calling supper.onBindViewHolder!
    super.onBindViewHolder(holder, position);

    Playlist playlist = mList.get(position);
    if (holder.title != null) {
        holder.title.setText(playlist.name);
    }
    if (holder.image != null) {
        Glide.with(mContext)
                .load(R.drawable.default_album_art)
                .into(holder.image);
    }
    PlaylistSongsLoader.getPlaylistSongList(mContext, playlist)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(songs -> {
                if (songs.size() > 0) {
                    if (holder.text != null) {
                        holder.text.setText(String.format(Locale.getDefault(),
                                "%d%s", songs.size(), songs.size() <= 1 ? " Song" : " Songs"));
                    }
                }
            });
    holder.itemView.setOnClickListener(view -> NavigationUtil.goToPlaylistNew(mContext, playlist));

}
 
Example 58
Project: VSPER   File: CourseNetworkService.java   Source Code and License 5 votes vote down vote up
public Observable<String> getFirstCourseName()
{
	return RetrofitBuilder.getInstance().groupList()
			.subscribeOn(Schedulers.io())
			.map(new Function<Elements, String>()
			{
				@Override
				public String apply(Elements elements) throws Exception
				{
					return elements.elements.get(0).getName();
				}
			});
}
 
Example 59
Project: ZhaZhaShop   File: MovieExpectingActivity.java   Source Code and License 5 votes vote down vote up
public void getMostExpectMovie() {
    RetrofitClient.getInstance()
            .apiMovieRankService()
            .getMostExpectMovie(10, offset)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<MostExpectMovieBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    showLoading();
                }

                @Override
                public void onNext(@NonNull MostExpectMovieBean mostExpectMovieBean) {
                    if (mostExpectMovieBean.getData().getMovies().size() > 0) {
                        offset += 10;
                        mMovieAdapter.addData(mostExpectMovieBean.getData().getMovies());
                        mMovieAdapter.loadMoreComplete();
                    } else {
                        mMovieAdapter.loadMoreEnd();
                    }

                    mTvContent.setText(mostExpectMovieBean.getData().getContent());
                    mTvCreateDate.setText(mostExpectMovieBean.getData().getCreated());
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    showError(ErrorHanding.handleError(e));
                }

                @Override
                public void onComplete() {
                    showContent();
                }
            });
}
 
Example 60
Project: Reactive-Android-Programming   File: Sandbox.java   Source Code and License 5 votes vote down vote up
private static void demo7() throws InterruptedException {
    Observable.just("One", "Two")
            .doOnNext(i -> log("doOnNext", i))
            .observeOn(Schedulers.computation())
            .subscribe(i -> log("subscribe", i));

    WAIT_LATCH.await();
}