将AsyncTask转换为RxAndroid

Fsh*_*mri 19 android android-asynctask rx-java rx-android

我有以下方法使用otto和发布对UI的响应AsyncTask.

private static void onGetLatestStoryCollectionSuccess(final StoryCollection storyCollection, final Bus bus) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            bus.post(new LatestStoryCollectionResponse(storyCollection));
            return null;
        }
    }.execute();
}
Run Code Online (Sandbox Code Playgroud)

我需要帮助将其转换AsyncTaskRxJava使用RxAndroid库.

Tar*_*360 13

不要使用.create()但是使用.defer()

Observable<File> observable = Observable.defer(new Func0<Observable<File>>() {
  @Override public Observable<File> call() {

    File file = downloadFile();

    return Observable.just(file);
  }
});
Run Code Online (Sandbox Code Playgroud)

要了解更多详细信息,请参阅https://speakerdeck.com/dlew/common-rxjava-mistakes


Lor*_*nMK 11

这是使用RxJava的文件下载任务的示例

Observable<File> downloadFileObservable() {
    return Observable.create(new OnSubscribeFunc<File>() {
        @Override
        public Subscription onSubscribe(Observer<? super File> fileObserver) {
            try {
                byte[] fileContent = downloadFile();
                File file = writeToFile(fileContent);
                fileObserver.onNext(file);
                fileObserver.onCompleted();
            } catch (Exception e) {
                fileObserver.onError(e);
            }
            return Subscriptions.empty();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

用法:

downloadFileObservable()
  .subscribeOn(Schedulers.newThread())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(observer); // you can post your event to Otto here
Run Code Online (Sandbox Code Playgroud)

这将在新线程上下载文件并在主线程上通知您.

OnSubscribeFunc已被弃用.代码已更新为使用OnSubscribeinsted.有关更多信息,请参阅Github上的问题802.

代码来自这里.


Mak*_*dov 6

在你的情况下你可以使用fromCallable.减少代码和自动onError排放.

Observable<File> observable = Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            File file = downloadFile();
            return file;
        }
    });
Run Code Online (Sandbox Code Playgroud)

使用lambdas:

Observable<File> observable = Observable.fromCallable(() -> downloadFile());
Run Code Online (Sandbox Code Playgroud)