首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android MediatorLiveData源代码订阅不会触发

Android MediatorLiveData源代码订阅不会触发
EN

Stack Overflow用户
提问于 2019-06-21 17:12:15
回答 1查看 1.1K关注 0票数 2

在我的项目中,我使用了稍微修改过的存储库模式:

  • DataSource (例如API、数据库)。提供实体的CRUD
  • 特定数据的存储库(例如UserRepository、SettingsRepository),它处理DataSources的协调(例如,从API调用更新数据库)。提供CRUD之上的基本功能。
  • ViewModel,它使用存储库并从存储库的调用中创建一个流(例如使用UserRepository同步用户数据,然后使用SettingsRepository同步用户的设置)
  • 视图是数据库的

在我的存储库中,我使用公开的LiveData<*>字段来通信状态--例如,said UserRepository将有一个公共类型的currentUser字段LiveData,私有MediatorLiveData,并且它将链接到保存要检索的当前用户ID的私有字段。

但是,由于某些原因,这些订阅(使用MediatorLiveData的addSource() {}方法)不会触发。

一个几乎1:1的例子(由NDA取代的模型名称)如下:

代码语言:javascript
复制
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进行的相同订阅在其他存储库中工作得很好,而且它们的构造方式与上面一样。

这里有什么问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-21 18:22:03

如果没有订阅任何观察者,MediatorLiveData将不会观察源LiveData。一旦您订阅了updateCurrentUser(),就会立即调用currentUser

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56707851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档