【问题标题】:Observe livedata in viewmodel to update UI through property binding观察 viewmodel 中的 livedata 以通过属性绑定更新 UI
【发布时间】:2019-04-06 21:18:49
【问题描述】:

我想观察ProfileViewModel 中的currentUser: LiveData<User> 属性(由UserRepository 公开)以更新user: User 属性。此属性通过数据绑定绑定到 UI,并且应在发生更改时更新 UI。这是我的假设。

我尝试使用 Transformations 设置 userproperty,但它不起作用。

一些代码? DatabaseService.kt

    fun getById(documentId: String): MutableLiveData<T> {
        val resultObj = MutableLiveData<T>()
        db.collection(className)
            .document(documentId)
            .get()
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val obj = task.result?.toObject(modelClass)
                    resultObj.value = obj
                } else {
                    Log.d(TAG, task.exception?.localizedMessage)
                }
            }
        return resultObj;
    }

UserRepository.kt

   fun getCurrentUser(): LiveData<User> {
        return this.getById(FirebaseAuthService.userUid)
    }

ProfileViewModel.kt

    // This doesn't work.
    val userRep = UserRepository();
    var user: User = User()

    init {
        Transformations.map(userRep.getCurrentUser()) { firebaseUser ->
            user = firebaseUser;
        }
    }

user: User 属性绑定到 UI。如何使用来自 livedata 对象的值更新此属性。我不想观察userRep.getCurrentUser()in 片段并持有对 UI 组件的引用并在发生更改时更新。

【问题讨论】:

  • 我怀疑问题是您需要在片段中调用binding.setLifecycleOwner()(参见proandroiddev.com/… 中的示例)
  • 太棒了!我已经尝试过了,它可以工作,谢谢!现在我必须明白它为什么有效。 :))
  • LiveData 对象的关键方面是它们具有生命周期感知能力 (developer.android.com/topic/libraries/architecture/livedata),因此通常需要存在于某个生命周期所有者的上下文中
  • 太棒了!谢谢约翰!

标签: android repository-pattern android-databinding android-livedata android-viewmodel


【解决方案1】:

当属性user 更改时,视图不会更新,因为它不知道它已更改。尝试使用MutableLiveData&lt;User&gt;

ProfileViewModel.kt

val userRep = UserRepository();
val user = MutableLiveData<User>(User())

init {
    Transformations.map(userRep.getCurrentUser()) { firebaseUser ->
        user.postValue(firebaseUser);
    }
}

这样做,视图将更新,因为user 属性中使用的LiveData 将通知它的更改。

【讨论】:

  • 这就是我现在所做的,比如var user: LiveData&lt;User&gt; = userRep.getCurrentUser() 这在我设置binding.setLifecycleOwner(this) 之前也不起作用,感谢@John O'Reilly 的回答。
  • 哦,我错误地认为你已经这样做了。很高兴看到你解决了它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
相关资源
最近更新 更多