![](/img/trans.png)
[英]Paging3: “Not sure how to convert a Cursor to this method's return type” when using PagingSource as return type in Room DAO
[英]Not sure how to convert a Cursor to this method's return type with DAO
我对 DAO 接口中的返回类型有疑问。 我已经进行了研究,并且尝试在不挂起/挂起的情况下进行,但仍然相同。
Error: Not sure how to convert a Cursor to this method's return type ...
道
@Query("SELECT * FROM notification_list ORDER BY id ASC")
abstract fun readAllDataState(): DataState<List<NotificationItemsResponse.NotificationItemData>>
我的用例:
class GetNotificationListItemDetailsUseCase @Inject constructor(private val notificationDao: NotificationDao): BaseFlowUseCase<Unit, DataState<List<NotificationItemsResponse.NotificationItemData>>>() {
override fun create(params: Unit): Flow<DataState<List<NotificationItemsResponse.NotificationItemData>>> {
return flow{
emit(DataState.Loading)
try {
emit(DataState.Success(notificationDao.readAllDataState()))
} catch(e: Exception) {
emit(DataState.Error(e)) // error, and send the exception
}
视图模型
val notificationData = MutableStateFlow<List<NotificationItemsResponse.NotificationItemData>>(emptyList())
[..]
fun getActualState() {
viewModelScope.launch {
getNotificationListItemDetailsUseCase.build(Unit).collect {
notificationData.value = it
Log.d("test2", "${notificationData.value}")
}
}
}
分段
GlobalScope.launch { collectNotificationItems() }
[..]
private suspend fun collectNotificationItems() {
vm.notificationData.collectLatest { dataState ->
when(dataState) {
is DataState.Error -> {
collectErrorState()
Log.d("collectNotificationItems", "Collect ErrorState")
}
DataState.Loading -> {
Log.d("collectNotificationItems", "Collect Loading")
}
is DataState.Success<*> -> {
vm.notificationData.collectWith(viewLifecycleOwner) {
notificationAdapter.items = it
notificationAdapter.notifyDataSetChanged()
Log.d("collectNotificationItems", "Collect Sucess")
}
}
}
}
上面有所有细节我希望它足以解决这个问题。
Room 不知道如何返回 DataState 类型。 readAllDataState()
的返回类型更改为List<NotificationItemsResponse.NotificationItemData>
并使 function suspend
,这样,每次调用只会获得一个值。 然后,只需将返回值包装在emit(DataState.Success(returnedValue))
中。 像这样:
@Query("SELECT * FROM notification_list ORDER BY id ASC")
abstract suspend fun readAllDataState(): List<NotificationItemsResponse.NotificationItemData>
class GetNotificationListItemDetailsUseCase @Inject constructor(private val notificationDao: NotificationDao): BaseFlowUseCase<Unit, DataState<List<NotificationItemsResponse.NotificationItemData>>>() {
override fun create(params: Unit): Flow<DataState<List<NotificationItemsResponse.NotificationItemData>>> =
flow {
emit(DataState.Loading)
try {
emit(DataState.Success(notificationDao.readAllDataState()))
} catch(e: Exception) {
emit(DataState.Error(e)) // error, and send the exception
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.