簡體   English   中英

在 android Room 中使用帶有 coruntineScope 的 viewModel 中的存儲庫函數

[英]Using the repository functions in the viewModel with coruntineScope in android Room

第一次使用 Androind 和 Room,我能夠按照一些代碼實驗室和教程來實現插入和顯示我的實體列表,但我似乎無法在我的 ViewModel 中使用我的其他 Repository 方法由於類型不匹配,這是我的 ViewModel 文件

class CustomerViewModel(application: Application) : AndroidViewModel(application) {

    // The ViewModel maintains a reference to the repository to get data.
    private val repository: CustomerRepository
    // LiveData gives us updated words when they change.
    val allCustomers: LiveData<List<Customer>>

    init {
        // Gets reference to Dao from db to construct
        // the correct repo.
        val customerDao = AppDatabase.getInstance(application).customerDao()
        repository = CustomerRepository(customerDao)
        allCustomers = repository.getCustomers()
    }

    fun insert(customer: Customer) = viewModelScope.launch {
        repository.insert(customer)
    }

}

我正在嘗試添加一個方法,例如

fun find(id: Int) = viewModelScope.launch {
        return repository.getCustomerByLocalId(id)
    }

但是ide說這里有類型不匹配? Required: Customer, Found: Job

這是我的存儲庫:

class CustomerRepository(private val customerDao: CustomerDao) {


    fun getCustomers(): LiveData<List<Customer>> = customerDao.getAlphabetizedCustomers()

    suspend fun getCustomerByLocalId(local_Id: Int): Customer =
        customerDao.customerByLocalId(local_Id)

    suspend fun insert(customer: Customer) {
        customerDao.insert(customer)
    }


    companion object {

        // For Singleton instantiation
        @Volatile
        private var instance: CustomerRepository? = null

        fun getInstance(customerDao: CustomerDao) =
            instance ?: synchronized(this) {
                instance ?: CustomerRepository(customerDao).also { instance = it }
            }
    }
}

CustomerDao 中的方法

@Query("SELECT * from customers ORDER BY name ASC")
    fun getAlphabetizedCustomers(): LiveData<List<Customer>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(customer: Customer)

    @Query("SELECT * FROM customers WHERE local_id = :localId")
    suspend fun customerByLocalId(localId: Int): Customer

編輯我嘗試了@lena-bru 的建議,但錯誤仍然存​​在,似乎有 2 個不同的,類型不匹配並且不應該返回。 你應該在不同的位置創建這個方法嗎? IDE 錯誤

改變這個:

   fun find(id: Int) = viewModelScope.launch {
        return repository.getCustomerByLocalId(id)
   }

對此:

   fun find(id: Int): Customer = viewModelScope.launch {
       withContext(Dispatchers.IO){
         repository.getCustomerByLocalId(id)
       }
   }

上面定義的 find 方法是無效的,它需要返回類型 Customer

您還需要提供上下文,並刪除 return 關鍵字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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