在我的项目中,我使用了稍微修改过的存储库模式:
在我的存储库中,我使用公开的LiveData<*>字段来通信状态--例如,said UserRepository将有一个公共类型的currentUser字段LiveData,私有MediatorLiveData,并且它将链接到保存要检索的当前用户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进行的相同订阅在其他存储库中工作得很好,而且它们的构造方式与上面一样。
这里有什么问题吗?
发布于 2019-06-21 18:22:03
如果没有订阅任何观察者,MediatorLiveData将不会观察源LiveData。一旦您订阅了updateCurrentUser(),就会立即调用currentUser。
https://stackoverflow.com/questions/56707851
复制相似问题