Android:Repository/ViewModel 中的业务逻辑转换

标签 android viewmodel repository-pattern

我有一个存储库类:

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 , ErrorLoading .

非常感谢!

最佳答案

您可以在发送到 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/

相关文章:

android - Firebase Android 应用程序 - 不更新实时数据库

Android ORMLite

android - 在软键盘键上显示多行/多个字符作为键标签

java - 如何使用 View 的子级制作绘图动画,逐个绘制每个 Path 的线?

android - 如何将 editText 值传递给 viewModel 和 Livedata (Kotlin)

c# - 实现返回从 EF 实体映射的域模型的 Repository<T>

javascript - 有没有办法用knockout完全分离模板和 View 模型?

c# - 如何仅使用获取访问器绑定(bind)到属性

java - JpaRepository findAll() 将不会返回具有空字段的行

c# - 如何使用 ADO.NET Entity Framework 测试存储库模式?