developers! I am trying to use RxJava in real project, but it seems like I didn't get the logic of it right. I need to create a list of objects in a new thread. And when it is done send this list to observer. What I have 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 as it is easy to see, list creates and fulfils in the main thread, so how to make it's creation in a brand new thread using rxJava?
What you want presumably is Observable.fromCallable().
Observable.fromCallable(() -> {
// init your list here
yourList = ....
Observable.fromIterable(yourList);
});
The inner code will be executed when a subscription happens. Thus, you may perform subscription on a thread you prefer.
Observable.create() would immediately be performed regardless subscription has happened or no, that's why it's adviced to use it with caution.
As stated in the post of Artem Zinnatullin:
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With