Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android RxJava, Non Blocking?

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?

like image 898
Alex Fu Avatar asked May 03 '14 16:05

Alex Fu


People also ask

Is RxJava dying?

RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself.

Is RxJava blocking?

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.

What is the replacement for RxJava?

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.

What is the advantage of RxJava in 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.


1 Answers

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.

like image 56
zsxwing Avatar answered Oct 19 '22 12:10

zsxwing