【发布时间】:2019-02-28 22:18:58
【问题描述】:
我正在尝试从数据库中读取对象列表并将其映射到另一种类型的列表。
// Returns either a Failure or the expected result
suspend fun getCountries(): Either<Failure, List<CountryItem>> {
// Get the result from the database
val result = countryLocalDataSource.getCountries()
// Left means Failure
if (result.isLeft) {
// Retrieve the error from the database
lateinit var error: Failure
result.either({
error = it
}, {})
// Return the result
return Either.Left(error)
}
// The database returns a List of Country objects, we need to map it to another object (CountryItem)
val countryItems: MutableList<CountryItem> = mutableListOf()
// Iterate the Country List and construct a new List of CountryItems
result.map { countries -> {
countries.forEach {
// Assign some values from an Enum (localized string resources)
val countryEnumValue = Countries.fromId(it.id)
countryEnumValue?.let { countryIt ->
val countryStringNameRes = countryIt.nameStringRes;
// Create the new CountryItem object (@StringRes value: Int, isSelected: Bool)
countryItems.add(CountryItem(countryStringNameRes, false))
}
}
} }
// Because this is a success, return as Right with the newly created List of CountryItems
return Either.Right(countryItems)
}
为了便于阅读,我没有包含整个 Repository 或 DAO 类,我在上面的代码 sn-p 中留下了 cmets。
简而言之:我正在使用 Kotlin 的 Coroutines 在单独的线程中访问数据库,并且我正在处理 UI Thread 上的响应。使用Either 类返回两个不同的结果(失败或成功)。
上面的代码可以用,但是太丑了。这是交付结果的正确方法吗?
我要做的是重构上面的代码。
整个问题是由两种不同的对象类型引起的。 Database Data Source API 正在返回一个Either<Failure, List<Country>>,同时该函数应该返回一个Either<Failure, List<CountryItem>>。
我无法直接从Database Data Source API 传递List<CountryItem>,因为Android Studio 不允许我编译项目(实体实现接口、编译错误等)。我想要实现的是以更好的方式映射Either 结果。
【问题讨论】: