尝试运行以下代码时获取编译错误:
如果我将返回类型更改为列表,则代码成功完全运行,但是我想从悬挂函数返回实时数据对象。
@Dao
interface TodoDao {
@Query("SELECT * from Todo where category_name = :category_name")
suspend fun getAllTodo(category_name : String) :LiveData<List<Todo>>
}
Compiler throws error: Not sure how to convert a Cursor to this method's return type (LiveData<List<Todo>>).
public abstract java.lang.Object getAllTodo(@org.jetbrains.annotations.NotNull()
def room_version = '2.1.0-beta01'
//Room
implementation "androidx.room:room-ktx:$room_version"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
//View model
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-beta01'
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0-beta01"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1"
任何帮助将不胜感激。谢谢
删除暂停cuz,当您说返回livedata时,它已经是暂停功能您的代码看起来像:
suspend suspend fun getAllTodo(category_name : String) :LiveData<List<Todo>>
这是正确的:
fun getAllTodo(category_name : String) :LiveData<List<Todo>>
但是,如果您要使用存储库,那么您需要在其中写暂停,但不要在dao中,不要忘记使用,例如在ViewModel,Coroutines中:
viewModelScope.launch(Dispatchers.IO){
...dao.getAllTodo(category_nam)...
}