android – Convert AsyncTask to RxAndroid-ThrowExceptions

Exception or error:

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

private static void onGetLatestStoryCollectionSuccess(final StoryCollection storyCollection, final Bus bus) {
    new AsyncTask<Void, Void, Void>() {
        protected Void doInBackground(Void... params) {
            return null;

I need help to convert this AsyncTask to RxJava using RxAndroid library.

How to solve:

Don’t use .create() but use .defer()

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

    File file = downloadFile();

    return Observable.just(file);

to know more details see


This is an example for a file download task using RxJava

Observable<File> downloadFileObservable() {
    return Observable.create(new OnSubscribeFunc<File>() {
        public Subscription onSubscribe(Observer<? super File> fileObserver) {
            try {
                byte[] fileContent = downloadFile();
                File file = writeToFile(fileContent);
            } catch (Exception e) {
            return Subscriptions.empty();


  .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.


In your case you can use fromCallable. Less code and automatic onError emissions.

Observable<File> observable = Observable.fromCallable(new Callable<File>() {
        public File call() throws Exception {
            File file = downloadFile();
            return file;

Using lambdas:

Observable<File> observable = Observable.fromCallable(() -> downloadFile());

Leave a Reply

Your email address will not be published. Required fields are marked *