It was my understanding that rxjava-android performs operations on a separate thread (when provided the correct Scheduler), leading to non-blocking operations, however a quick and dirty test seems to prove this to be incorrect.
I used the following code snippets and in both, scenarios, the UI was being blocked...
Snippet 1
Observable observable = Observable.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
int i = 0;
while (i == 0) {}
subscriber.onCompleted();
}
});
observable.subscribeOn(Schedulers.newThread());
observable.observeOn(AndroidSchedulers.mainThread());
observable.subscribe();
Snippet 2
Observable observable = Observable.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
SystemClock.sleep(5000);
subscriber.onCompleted();
}
});
observable.subscribeOn(Schedulers.newThread());
observable.observeOn(AndroidSchedulers.mainThread());
observable.subscribe();
Am I missing something here?
RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself.
Usually, asynchronous code is non-blocking: You call a method that returns immediately, allowing your code to continue its execution. Once the result of your call is available, it is returned via a callback. RxJava is asynchronous, too. And it is blocking as well — at least by default.
As Coroutines are written using standard Kotlin, this library is suitable for new Android projects since Google announced Kotlin as the new language for Android.
RxJava is a Java library that enables Functional Reactive Programming in Android development. It raises the level of abstraction around threading in order to simplify the implementation of complex concurrent behavior.
The mistake is that you use the wrong Observable
. The correct code should be:
Observable observable = Observable.create(new Observable.OnSubscribe<Object>() {
@Override
public void call(Subscriber<? super Object> subscriber) {
int i = 0;
while (i == 0) {}
subscriber.onCompleted();
}
});
observable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe();
Both subscribeOn
and observeOn
return a new Observable which implements their functions. But the original Observable is not modified. Actually, every operator will always create a new Observable without modifying the original one.
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