[英]Return value from thread (runnable)
我正在與Room一起使用來保存數據,使用新的AAC來保存數據,並且我正在開發一個應用程序,其中Google github存儲庫中提供的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);
}
我在這里想念什么??
那是因為這里有2個線程 。
當您調用readTransaction()
然后調用readTransaction()
mAppExecutors.diskIO().execute(readRunnable)
,方法readTransaction()
立即返回並調用LOGD(TAG, "sanitizeCategoriesList size after: " + mCategories);
,按預期打印null
。 在此期間,異步上第二螺紋, run()
被執行時,在結束調用onReadTransactionCompleted()
最后設定mCategories
值。
因此,僅在調用onReadTransactionCompleted()
之后才能依賴於mCategories
。
如果您將mCategories
用於UI相關的內容,則可能要考慮使用AsyncTask並將代碼從run()
移至doInBackground()
並將代碼從onReadTransactionCompleted()
移至onPostExecute()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.