从线程返回值(可运行)

时间:2018-04-17 19:22:32

标签: android dao runnable android-room

我正在与Room合作以保留数据,新的AAC用于保存数据,我正在使用Google's github repository中提供的Todo应用作为我们蓝图的应用。 我一直在尝试获取在实体上执行的事务返回的值。我使用全局变量mCategories来检索和存储返回的数据,但我继续返回一个空对象。

这是我的代码:

 public interface LoadDataListener<T>
{
    void onReadTransactionCompleted(T arg);
}

private void readTransaction(final LoadDataListener<List<Category>> loadDataListener, final boolean onlyClassic)
{
    Runnable readRunnable = new Runnable() {
        @Override
        public void run() {
            List<Category> categories;
            if (!onlyClassic)
                categories = mCategoryDAO.loadAllSellingCategories();
            else
                categories = mCategoryDAO.loadAllClassicCategories();

            LOGD(TAG, "Category size: "+ categories.size());
            // The log above reads a value > 0
            loadDataListener.onReadTransactionCompleted(categories);
        }
    };

    mAppExecutors.diskIO().execute(readRunnable);
}

private List<Category> getSanitizedAndPersistedCategories(boolean onlyClassic) {
    readTransaction(new LoadDataListener<List<Category>>() {
        @Override
        public void onReadTransactionCompleted(List<Category> arg) {
            mCategories = arg;
            LOGD(TAG, "sanitizeCategoriesList size before: " + mCategories);
            // The log above reads a value > 0

        }
    }, onlyClassic);

    LOGD(TAG, "sanitizeCategoriesList size after: " + mCategories);
    // The log above reads null
    return sanitizeCategoriesList(mCategories);
}

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

那是因为你在这里有 2个帖子 当您致电readTransaction()然后mAppExecutors.diskIO().execute(readRunnable)时,方法readTransaction()会立即返回并调用LOGD(TAG, "sanitizeCategoriesList size after: " + mCategories);,这会按预期打印null。在此期间,在第二个线程上异步执行run(),在末尾onReadTransactionCompleted()调用并最终设置mCategories值。

因此,您只能在mCategories被调用后依赖onReadTransactionCompleted()

如果您使用mCategories用于与UI相关的内容,则可能需要考虑使用AsyncTask并将代码从run()移至doInBackground(),并将代码从{{1}移至{} } onReadTransactionCompleted()

相关问题