本文介绍了Room Dao LiveData 作为返回类型导致编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Room 并实现了返回 LiveDataDao.添加了以下依赖项后,它运行良好.

I am using Room and implemented Dao that returns LiveData. It was working fine with below dependency added.

implementation "androidx.room:room-runtime:2.1.0-alpha04"
kapt "androidx.room:room-compiler:2.1.0-alpha04"

但是当我添加新的 Room 协程依赖项时,如下所述.

But when I added new Room coroutine dependency as mentioned below.

implementation "androidx.room:room-runtime:2.1.0-alpha04"
implementation "androidx.room:room-coroutines:2.1.0-alpha04"
kapt "androidx.room:room-compiler:2.1.0-alpha04"

下面是编译代码

@Dao
interface AccountDao{

    @Query("SELECT * FROM account_master")
    suspend fun getAllAccounts(): List<Account>
}

下面是出错的代码.

@Dao
interface AccountDao{

    @Query("SELECT * FROM account_master")
    suspend fun getAllAccounts(): LiveData<List<Account>>
}

开始接收错误.

PlayGround/app/build/tmp/kapt3/stubs/debug/com/playground/www/x/datasource/dao/AccountDao.java:11: error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.LiveData<java.util.List<com.playground.www.x.datasource.entity.Account>>).
public abstract java.lang.Object getAllAccounts(@org.jetbrains.annotations.NotNull()

有人遇到过类似的问题吗?

Any one facing similar issue?

推荐答案

我认为这里的解决方案实际上是不使用协程返回 LiveData.LiveData 开箱即用,返回 LiveData 时没有理由使用协程.

I think the solution here is actually to just return the LiveData without using Coroutines. LiveData works out of the box, there's no reason to use Coroutines when returning LiveData.

当使用 LiveData 时,它已经在后台线程上处理它.如果不使用 LiveData,那么在这种情况下,您可以使用协程(可能最终是协程通道)或 RxJava2.

When using LiveData it already handles it on a background thread. When NOT using LiveData then in that case you can use Coroutines (and maybe eventually Coroutines Channels) or RxJava2.

查看此代码实验室的示例:https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin.在这里,他们需要一个用于插入的后台线程,而不是用于返回的 LiveData.

See this codelab for an example: https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin. Here they need a background thread for inserts but not for the returned LiveData.

注意:实际代码实验室中似乎存在一个错误,即 DAO 没有返回 LiveData.我已在下面的示例中更正了这一点.

Note: there seems to be a mistake in the actual codelab where the DAO is not returning a LiveData. I've corrected that in the sample below.

@Dao
interface WordDao {

    @Query("SELECT * from word_table ORDER BY word ASC")
    fun getAllWords(): LiveData<List<Word>>

    @Insert
    suspend fun insert(word: Word)

    @Query("DELETE FROM word_table")
    fun deleteAll()
}

class WordRepository(private val wordDao: WordDao) {

    val allWords: LiveData<List<Word>> = wordDao.getAllWords()

    @WorkerThread
    suspend fun insert(word: Word) {
        wordDao.insert(word)
    }
}

这篇关于Room Dao LiveData 作为返回类型导致编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:38
查看更多