我有一个存储库类:
class RepositoryImpl(private val application: Application) :
Repository {
override suspend fun getCities(): Resource<List<City>> =
try {
val bufferReader = application.assets.open(CITIES_FILE_NAME).bufferedReader()
val data = bufferReader.use {
it.readText()
}
val gson = GsonBuilder().create()
val type: Type = object : TypeToken<ArrayList<City?>?>() {}.type
val fromJson = gson.fromJson<List<City>>(data, type)
Resource.Success(fromJson)
} catch (e: JsonSyntaxException) {
Resource.Error(JSONSYNTAXEXCEPTION_ERROR_MESSAGE)
} catch (e: IOException) {
Resource.Error(IOEXCEPTION_ERROR_MESSAGE)
}
和 Resource
类是:
sealed class Resource<T>(
val data: T? = null,
val message: String? = null
) {
class Success<T>(data: T) : Resource<T>(data)
class Loading<T>(data: T? = null) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
}
我需要获取城市,我在我的 VM 中这样做:
class CityListViewModel(private val repository: Repository) : ViewModel() {
@VisibleForTesting
val allCities: LiveData<Resource<List<City>>> =
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emit(Resource.Loading())
val cities: Resource<List<City>> = repository.getCities().sortedBy { city: City -> city.name }
emit(cities)
}
}
问题是我对存储库建模以将城市列表包装在 Resource
中我需要按字母顺序对城市进行排序,所以行 val cities: Resource<List<City>> = repository.getCities().sortedBy { city: City -> city.name }
不编译。
我这样做错了吗?存储库只负责检索数据并将其包装在 Resource
中。业务逻辑位于 VM 中,但现在它收到一个 Resource
并且需要访问数据,对其进行排序,然后将其放回 Resource
中所以 Activity
知道该怎么做取决于它是否是 Success
, Error
或 Loading
.
非常感谢!
最佳答案
您可以在发送到 UI 之前映射您的数据:
...
emit(Resource.Loading())
val resource = repository.getCities().map {
if (it is Resource.Success) {
Resource.Success(it.data.sortedBy { city: City -> city.name })
} else {
it
}
}
emit(resource)
...
关于Android:Repository/ViewModel 中的业务逻辑转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59555435/