![](/img/trans.png)
[英]Android MVVM architecture and observing changes on data from an API
[英]Selecting Data from Room without observing
我需要從表中獲取 select 數據,對其進行操作,然后將其插入到另一個表中。 這只發生在當天第一次打開應用程序並且不會在 UI 中使用時。 我不想使用 LiveData,因為它不需要被觀察,但是當我研究如何做到這一點時,大多數人都說我應該使用 LiveData。 我嘗試過使用 AsyncTask,但出現錯誤“無法訪問主線程上的數據庫,因為它可能......”。 這是我的 AsyncTask 的代碼
public class getAllClothesArrayAsyncTask extends AsyncTask<ArrayList<ClothingItem>, Void, ArrayList<ClothingItem>[]> {
private ClothingDao mAsyncDao;
getAllClothesArrayAsyncTask(ClothingDao dao) { mAsyncDao = dao;}
@Override
protected ArrayList<ClothingItem>[] doInBackground(ArrayList<ClothingItem>... arrayLists) {
List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray();
ArrayList<ClothingItem> arrayList = new ArrayList<>(clothingList);
return arrayLists;
}
}
這就是我在活動中的稱呼
mClothingViewModel = new ViewModelProvider(this).get(ClothingViewModel.class);
clothingItemArray = mClothingViewModel.getClothesArray();
在這種情況下,最佳做法是什么?
簡要總結:
使用啟用 lambdas 的線程切換的幾個示例(如果您出於某種目的不想學習更高級的東西) :
只是一個線程
new Thread(() -> { List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray(); //... next operations });
執行者
Executors.newSingleThreadExecutor().submit(() -> { List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray(); //... next operations });
異步任務
AsyncTask.execute(() -> { List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray(); //... next operations });
如果您使用存儲庫模式,您可以將所有這些線程切換放在那里
另一個有用的鏈接來閱讀 AsyncTask 棄用后的生活
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.