ViewModel 中的 LiveData 变量以及将数据传递到 View 时出现问题

问题描述 投票:0回答:1

Github项目链接

这是我的项目,如果您有时间看一下它的内容,我将不胜感激。

所以我的 LoginViewModel.kt 我有两个变量和一些在 LiveData 上工作的乐趣:

private val _loggedInUser = MutableLiveData<User?>()
var loggedInUser: LiveData<User?> = _loggedInUser

我还为这个变量获取了函数:

private fun fetchLoggedInUser(username: String) {
        viewModelScope.launch {
            val user = userRepository.getUserByUsername(username)
            Log.d("LoginViewModel", "Fetched user: $user")
            _loggedInUser.value = user

            if (user != null) {
                Log.d("LoginViewModel", "_loggedInUser set to: ${_loggedInUser.value}")
                Log.d("LoginViewModel", "loggedInUser set to: ${loggedInUser.value}")

            } else {
                Log.d("LoginViewModel", "No user found for username: $username")
            }
        }
    }

此函数在用户登录函数中也在 LoginViewModel 中调用:

fun login(navController: NavController) {
        viewModelScope.launch {
            usernameErrorMessage = null
            passwordErrorMessage = null

            val hashedInputPassword = hashPassword(password)

            val user = userRepository.getUser(username, hashedInputPassword)

            if (user != null) {
                // Pobierz dane użytkownika
                fetchLoggedInUser(username)
                loginSuccess = true

                // Przekazanie nazwy użytkownika do HomepageView
                navController.navigate("HomepageView/${user.username}")
            } else {
                usernameErrorMessage = "Invalid username or password"
                passwordErrorMessage = "Invalid username or password"
            }
        }
    }

日志显示正在分配变量:

2024-10-02 20:45:02.497  7595-7595  LoginViewModel          com.example.pracainynierska          D  Fetched user: User(id=1, username=Andrzej, password=03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4, [email protected], userPhotoPath=app/src/main/res/raw/user_photo_2.json)
2024-10-02 20:45:02.497  7595-7595  LoginViewModel          com.example.pracainynierska          D  _loggedInUser set to: User(id=1, username=Andrzej, password=03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4, [email protected], userPhotoPath=app/src/main/res/raw/user_photo_2.json)
2024-10-02 20:45:02.497  7595-7595  LoginViewModel          com.example.pracainynierska          D  loggedInUser set to: User(id=1, username=Andrzej, password=03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4, [email protected], userPhotoPath=app/src/main/res/raw/user_photo_2.json)

但是这个有趣的事情告诉我 val userId 为 null,这也在 LoginViewModel 中:

fun updateUserPhotoPath(photoPath: String) {
        val userId = loggedInUser.value?.id
        Log.d("UserImagePicker", "User ID before updating photo path: ${loggedInUser.value?.id}")
        Log.d("UserImagePicker", "New photo path: $photoPath")

        if (userId != null) {
            Log.d("LoginViewModel", "Updating user photo path for userId: $userId with photoPath: $photoPath")
            viewModelScope.launch {
                //userRepository.updateUserPhotoPath(userId, photoPath)
            }
        } else {
            Log.d("LoginViewModel", "User ID is null, cannot update photo path.")
        }
    }

在 HomepageView 中,我有变量loggedInUser,它也显示为空:

val loggedInUser by loginViewModel.loggedInUser.observeAsState()

**我不知道如何从 ViewModel 和 UI(View) 中的 LiveData 变量读取数据,有人可以帮忙吗? **

我不知道如何从 ViewModel 和 UI(View) 中的 LiveData 变量读取数据,有人可以帮忙吗?

android kotlin mvvm android-livedata mutablelivedata
1个回答
0
投票

尝试将

liveData/mutableLiveData
替换为
StateFlow/MutableStateFlow
,将
observeAsState()
替换为
collectAsStateWithLifecycle()

© www.soinside.com 2019 - 2024. All rights reserved.