I created an Observable using the Observable.fromCallable
method and subscribed to it as shown in the code snippet below.
Observable<String> stringObservable = Observable.fromCallable(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return Thread.currentThread().getName();
}
});
stringObservable.subscribeOn(Schedulers.io());
stringObservable.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String aDouble) {
Toast.makeText(SimpleActivity.this, "onNext: " + aDouble,
Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable e) {
new AlertDialog.Builder(SimpleActivity.this)
.setTitle("Error")
.setMessage(e.toString())
.show();
}
@Override
public void onComplete() {
}
});
The snippet above produced a toast showing that the Callable was run on the main thread instead of the Schedulers.io thread. What's happening?
Every operation on an Observable creates a new instance and does not effect the original one. Therefore
stringObservable.subscribeOn(Schedulers.io());
does not affect your code below.
The correct way of using them would be in a chain instead of using a variable.
Observable.fromCallable(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return Thread.currentThread().getName();
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String aDouble) {
Toast.makeText(SimpleActivity.this, "onNext: " + aDouble,
Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable e) {
new AlertDialog.Builder(SimpleActivity.this)
.setTitle("Error")
.setMessage(e.toString())
.show();
}
@Override
public void onComplete() {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With