我有一个存储库类:
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之前先对其进行映射:
您可以发出排序结果,如下所示: