簡體   English   中英

在初始化時觀察 viewmodel 內的 livedata

[英]Observe a livedata inside viewmodel at init

所以每次我的應用程序啟動時,如果用戶登錄,我會從 firestore 獲取一個User文檔。該文檔包含有關用戶的所有信息。 我必須在整個應用程序的各種活動中顯示這些信息。

現在,我不想每次想在任何片段/活動中顯示用戶數據時都observe文檔。 因此,我在我的UserViewModel中保留了文檔的本地副本作為 Kotlin 數據 class 可以立即用於顯示用戶數據(無異步調用)。 不過,這里的問題是,如果用戶的文檔得到更新,我希望更改反映在我的本地副本中,為此我想觀察我的 ViewModel 中的文檔。 這是我的一些代碼:

fun observeUserProfile(userId: String): MutableLiveData<User> {
        val res = MutableLiveData<User>()

        DatabaseService.getDbInstance()
            .collection("users")
            .document(userId)
            .addSnapshotListener { snap, e ->
                if (e != null) {
                    Log.d("UserRepository", "Error while observing $userId, error: $e")
                }

                if (snap != null && snap.exists()) {
                    res.value = CustomUtils.convertToUser(snap)
                    Log.d("UserRepo", "Fetched user: ${res.value}")
                } else res.value = null
            }

        return res
    }

本 function 觀察文檔。 這是我的 ViewModel init function:

val currentUid = MutableLiveData<String>()
var currentUser = MutableLiveData<User>()

init {
    val uid = application.getSharedPreferences("myappd", Context.MODE_PRIVATE)
        .getString("user_uid", null)

    if (uid != null) {
        currentUid.value = uid
        currentUser = observeUser(uid) // Think the problem is here
    }
}

當我執行userViewModel.currentUser.value時,我經常收到NullPointerException 我這樣做的想法是擁有一個本地副本,我可以立即顯示而不是每次都觀察,同時還保持本地副本更新到 firestore 文檔。 是否需要為當前用戶創建 LiveData? 我究竟做錯了什么?

為什么要從observeUserProfile

也許在這個 function 中設置currentUser實時數據值會更好:

val currentUid = MutableLiveData<String>()
val currentUser = MutableLiveData<User>()

init {
    val uid = application.getSharedPreferences("myappd", Context.MODE_PRIVATE)
        .getString("user_uid", null)

    if (uid != null) {
        currentUid.value = uid
        observeUser(uid)
    }
}

fun observeUserProfile(userId: String) {
        DatabaseService.getDbInstance()
            .collection("users")
            .document(userId)
            .addSnapshotListener { snap, e ->
                if (e != null) {
                    Log.d("UserRepository", "Error while observing $userId, error: $e")
                }

                if (snap != null && snap.exists()) {
                    currentUser.value = CustomUtils.convertToUser(snap)
                }
            }
}

在這種情況下,我們可以觀察currentUser值,如果我們在 observeUserProfile 中獲得值,它會立即傳遞給觀察者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM