Truong Giang Dam
Truong Giang Dam

Reputation: 500

Why am I able to access the view inside onNext method RxAndroid inspite of not set observeOn(AndroidSchedulers.mainThread())?

I am researching into RxJava/RxAndroid. I decided to create Observable via Observable.fromCallable method because of it gives us two important things:

  1. The code for creating the emitted value is not run until someone subscribes to the Observerable
  2. The creation code can be run on a different thread.

I have wrote the sample as below:

private void testObservableFromCallable() {
    Observable<String> stringObservable = Observable.fromCallable(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "Hello";
        }
    });

    Subscription subscription = stringObservable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(String s) {
                    Log.d("LOG_TAG", "Thread name: " + Thread.currentThread().getName());
                    textView.setText(s);
                }
            });
}

Every things are ok. It work fine and log tag show thread name is main. It means onNext() method be called on mainThread() and textView be accessed properly.

Now what am I confusing is when I remove this line observeOn(AndroidSchedulers.mainThread()) or just change it to observeOn(Schedulers.io()). Both of two cases the log tag show thread name is RxIoScheduler. That is not main thread, but the app compile with no error and textView show the text "Hello" on the screen.

Anyone help me explain why am I able to access to the view outside main thread?. Thanks so much!

Upvotes: 0

Views: 117

Answers (1)

laalto
laalto

Reputation: 152807

The framework usually does not do anything to check that you're really on the main thread. As a caller, it's your responsibility.

Some but not all UI widget access on non-main thread lead to a crash. Here you're being "lucky" that the thread problem goes undetected with your method call.

Upvotes: 1

Related Questions