0
votes

http://blog.danlew.net/2015/07/23/deferring-observable-code-until-subscription-in-rxjava/ discusses creating observables using Observable.just, Observable.create, and Observable.defer

Let's say I have this:

List<File> fileIOFunction() {
    // does some file io operations
}

OBSERVABLE.subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())

What thread do the file io operations run on if OBSERVABLE is:

Observable.create(
                new Observable.OnSubscribe<List<File>>() {
                    @Override
                    public void call(Subscriber<? super List<File>> 
                                     subscriber) {
                        subscriber.onNext(fileIOFunction());
                 }

If OBSERVABLE is Observable.just(fileIOFunction())

If OBSERVABLE is

Observable.defer(new Func0<Observable<List<File>>>() {
                @Override
                public Observable<List<File>> call() { 
                    return Observable.just(fileIOFunction());
                });
1
You could simply try it by adding System.out.println(Thread.currentThread()) to fileIOFunction(), implement both cases and run them. - akarnokd
Thanks! I did not know about Thread.currentThread(). Attach getName() to print which thread. - Marc

1 Answers

1
votes

For just it will run on calling thread, because fileIOFunction() will be invoked eagerly. Defer and Create will run on Schedulers.io() due to subscribeOn and will switch to AndroidSchedulers.mainThread() due to observeOn (switch thread). Create and Defer are lazy.