Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

rx java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...