Convert AsyncTask to RxAndroid

后端 未结 3 1793
北恋
北恋 2021-02-04 03:02

I have the following method to post response to UI using otto and AsyncTask.

private static void onGetLatestStoryCollectionSuccess(final StoryColle         


        
3条回答
  •  不要未来只要你来
    2021-02-04 03:54

    This is an example for a file download task using RxJava

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

    Usage:

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

    This would download the file on a new thread and notify you on the main thread.

    OnSubscribeFunc was deprecated. Code updated to use OnSubscribe insted. For more info see issue 802 on Github.

    Code from here.

提交回复
热议问题