Java – RxJava 2 creates lists in a new thread

RxJava 2 creates lists in a new thread… here is a solution to the problem.

RxJava 2 creates lists in a new thread

Developers!
I’m trying to use RxJava in a real project, but it seems I’m not understanding the correct logic. I need to create a list of objects in a new thread. Send this list to the observer when finished. What I found is:

LinkedList<IntroSliderElement> list = new LinkedList<>();
    list.add(new IntroSliderElement(0, "test 0", 0));
    list.add(new IntroSliderElement(1, "test 1", 1));
    list.add(new IntroSliderElement(2, "test 2", 2));

Observable<LinkedList<IntroSliderElement>> listObserv = Observable.just(list);
    listObserv
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<IntroSliderElement>>() {
                @Override
                public void onSubscribe(Disposable d) {

}

@Override
                public void onNext(List<IntroSliderElement> value) {
                    view().render(new IntroModel.OnFirstSliderElement((LinkedList<IntroSliderElement>) value));
                }

@Override
                public void onError(Throwable e) {

}

@Override
                public void onComplete() {

}
            });

But it’s easy to see that list is created and executed in the main thread, so how do you create it in a whole new thread using rxJava?

Solution

What you want is probably Observable.fromCallable() .

Observable.fromCallable(() -> {
     init your list here
    yourList = ....
    Observable.fromIterable(yourList);
});

The internal code is executed when the subscription occurs.
Thus, you can perform subscriptions on your favorite threads.

Observable.create() will be executed immediately, regardless of whether the subscription occurs or not, which is why it is recommended to use it sparingly.

As Artem Zinnatullin’s post states:

Don’t use Observable.create() if you can, it’s very easy to shoot yourself in the foot! (and then shoot again for each new subscriber!)

Related Problems and Solutions