簡體   English   中英

從房間中選擇數據而不觀察

[英]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();

在這種情況下,最佳做法是什么?

簡要總結

  1. Room 真的不允許在主線程上做任何事情(查詢|插入|更新|刪除)。 您可以在 RoomDatabaseBuilder 上關閉此控件,但最好不要。
  2. 如果您不關心 UI,至少可以將您的 ROOM 式代碼(可運行)放到線程、執行程序、異步任務之一(但去年已棄用)...我在下面放了示例
  3. 我認為對 DB 進行一次性操作的最佳實踐是協程(適用於在項目中使用 Kotlin 的人)和 RxJava(適用於使用 Java 的人,Single|Maybe 作為返回類型)。 它們提供了更多可能性,但您應該投入時間來了解這些機制的意義。
  4. 從 Room 觀察數據 stream 有 LiveData、Coroutines Flow、RxJava(Flowable)。

使用啟用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM