arraylist不在onNext方法外部更新

时间:2019-06-05 15:43:56

标签: android rx-java rx-java2

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

1 个答案:

答案 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());