AndroidRX - run method in background
With RxJava2 a possible solution is:
Version with lambdas:
Single.fromCallable(() -> loadInBackground())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((resultObject) -> { updateUi(resultObject) });
Version without lambdas:
Single.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
return loadInBackground();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object resultObject) throws Exception {
updateUi(resultObject);
}
});
Example methods used above:
private Object loadInBackground() {
// some heavy load code
return resultObject;
}
private void updateUi(Object resultObject) {
// update your Views here
}
According to docs
Deprecated: fromFunc0 Unnecessary now that Func0 extends Callable. Just call fromCallable(java.util.concurrent.Callable) instead.
So you could make the call in this way:
Observable.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
return someMethod();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
@Override
public void call(Object object) {
}
});
Your doHeavyStuff() executes computation on calling thread, you just wrap your result into Observable. In order to wrap computation into observable you should use defer
Observable.defer(new Func0<Observable<Integer>>() {
@Override
public Observable<Integer> call() {
return Observable.just(doHeavyStuff());
}
});
then you can specify threads by subscribeOn and observeOn methods