21

I want to run a method in background using rxjava. I don't care about the result.

void myHeavyMethod() { (...) }

So far the only solution I have is to modify the return type to e.g. boolean.

boolean myHeavyMethod() { (...) return true; }

Afterwards I run:

Completable.defer(() -> Completable.fromCallable(this::myHeavyMethod))
        .subscribeOn(Schedulers.computation())
        .subscribe(
                () -> {},
                throwable -> Log.e(TAG, throwable.getMessage(), throwable)
        );

Is there a way to do it keeping the void return type?

1 Answer 1

43

The fromAction() method is what you're looking for.

Completable.fromAction(this::myHeavyMethod)
3
  • I get an error "Method reference not supported at this language level"
    – RunLoop
    Nov 17, 2017 at 4:30
  • Method references are a Java 8 feature. So you're maybe using Java 7 and thus you have to implement the Action interface yourself.
    – tynn
    Nov 17, 2017 at 10:13
  • 4
    don't forget to call .subscribe()
    – Mehran
    Nov 7, 2018 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.