引言:
我根据以下示例创建了一个android项目:https://github.com/android/architecture-samples/
我必须添加一个保存响应状态(成功/错误)及其值的类,在存储库中它基本上像这样:
sealed class Result<out R> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
它比经典的要好:
class Result<T> (
val success: Boolean,
val data: T?,
val exception: Exception?
)
因为:-在这种情况下,成功结果肯定只有data
,而错误只有exception
。-由于Kotlin Smart Casts,成功消息和错误消息都从Result继承,因此验证看起来更简单:
var responce: Result<DataEntity> = dataSource.GetData()
if (responce is Success) {
doSomethingWith(responce.data)
} else if (responce is Error) {
throw responce.exception
}
问题:
很好,但是当我尝试异步观察来自本地数据源(使用Room lib)的数据时:
interface TaskDao {
@Query("SELECT * FROM tasks")
fun observeTasks(): LiveData<List<TaskEntity>>
}
class SqlLocalDataSource(
private val taskDao: TaskDao,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
): LocalDataSource {
override suspend fun observeTasks(): LiveData<Result<List<TaskEntity>>> = withContext(ioDispatcher) {
taskDao.observeTasks().map {
Success(it)
}
}
}
它给我以下错误:Type inference failed. Expected type mismatch: inferred type is LiveData<Result.Success<List<TaskEntity>>> but LiveData<Result<List<TaskEntity>>> was expected
这很奇怪,因为成功继承自结果
我尝试:
问题是它不允许在暂停功能中使用LiveData,在我将功能更改为非暂停后,错误消失了:
override fun observeTasks(): LiveData<Result<List<TaskEntity>>> {
return taskDao.observeTasks().map {
Success(it)
}
}
也许有人可以解释为什么?