ArrayList已在onNext中更新,但在ArrayList外部未更新。
mListItems.clear(); //size = 0
compositeDisposable.add(Observable.create(handler)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(category -> {
mListItems.add(category); //size = 3
notifyDataSetChanged();
})
.subscribe());
mListItems.forEach(this::expandAllParent); //size = 0
答案 0 :(得分:0)
这是因为RxJava
代码块运行asynchronously
是因为您正在IO线程上订阅它,这意味着该线程不是android主线程,因此不保证doOnNext
链中的代码将在RxJava
内部的代码之前执行。我的意思是执行顺序是这样的:
mListItems.clear(); // -> first this line gets executed
// Here and observable gets created and passed to another thread to get execute by that thread
compositeDisposable.add(Observable.create(handler)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(category -> {
mListItems.add(category);
notifyDataSetChanged(); // and at last this block of code gets executed
})
subscribe());
mListItems.forEach(this::expandAllParent); // -> secondly this line gets executed
如果您要为所有添加的项目正确执行expandAllParent
,则最好在doOnNext
方法内移动该行代码,如下所示:
mListItems.clear();
compositeDisposable.add(Observable.create(handler)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(category -> {
mListItems.add(category);
notifyDataSetChanged();
mListItems.forEach(this::expandAllParent); // -> move this here
})
subscribe());