【发布时间】:2019-06-21 17:12:15
【问题描述】:
在我的项目中,我使用了稍微修改的存储库模式:
- 数据源(例如 API、数据库)。提供实体的 CRUD
- 特定数据的存储库(例如 UserRepository、SettingsRepository),用于处理数据源的协调(例如,通过 API 调用更新数据库)。提供高于 CRUD 的基本功能
- 使用存储库并从存储库调用创建流程的 ViewModel(例如,使用 UserRepository 同步用户数据,然后使用 SettingsRepository 为用户同步设置)
- 视图是数据绑定的
在我的存储库中,我使用公开的 LiveData 字段来传达状态 - 例如说 UserRepository 将有一个公共类型 LiveData、私有 MediatorLiveData 的 currentUser 字段,并且它将链接到一个私有字段,该字段包含要检索的当前用户 ID。
但是,出于某种原因,这些订阅(使用 MediatorLiveData 的 addSource() {} 方法)不会触发。
一个几乎 1:1 的示例(由于 NDA 替换了型号名称)如下:
abstract class BaseRepository: ViewModel(), KoinComponent {
val isLoading: LiveData<Boolean> = MutableLiveData<Boolean>().apply { postValue(false) }
}
class UserRepository: BaseRepository() {
private val client: IClient by inject() // Koin injection of API client
private val sharedPref: SharedPrefManager by inject() // custom wrapper around SharedPreferences
private val currentUserId = MutableLiveData()
val currentUser: LiveData<User> = MediatorLiveData()
val users: LiveData<List<User>> = MutableLiveData()
init {
(currentUser as MediatorLiveData).addSource(currentUserId) { updateCurrentUser() }
(currentUser as MediatorLiveData).addSource(users) { updateCurrentUser() }
(currentUserId as MutableLiveData).postValue(sharedPref.getCurrentUserId())
// sharedPref.getCurrentUserId() will return UUID? - null if
}
fun updateCurrentUser() {
// Here I have the logic deciding which user to push into `currentUser` based on the list of users, and if there's a `currentUserId` present.
}
}
通过实施此示例,updateCurrentUser() 永远不会被调用,即使对其他 LiveData 字段的订阅发生并且在对 currentUser 对象进行调试时可见。
通过addSource 进行的相同订阅在其他存储库中也可以正常工作,并且它们的构建方式与上述完全相同。
这里可能出了什么问题?
【问题讨论】:
标签: android android-livedata mutablelivedata