Working on a project in Kotlin in AndroidStudio, fairly basic stuff, but MutableLiveData is not working like I expect it to. Am I doing something wrong or maybe I'm confused on how it works?
I'm using a viewModel to handle the LiveData and for testing purposes rn am just running some code in a fragment's onCreate method:
ViewModel
class UserViewModel : ViewModel() {
var currentUser: User = DataSource.user
private var _selectedSkillPoints = MutableLiveData<Int>(currentUser.selectedSkill.points)
val selectedSkillPoints: LiveData<Int> = _selectedSkillPoints
...
}
Fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
private var user: User = DataSource.user
user.selectedSkill.points++
MaterialAlertDialogBuilder(requireContext())
.setMessage("user.selectedSkill.points = ${user.selectedSkill.points} \n sharedViewModel.selectedSkillPoints.value = ${sharedViewModel.selectedSkillPoints.value} ")
.show()
}
I would expect that updating currentUser.points also updates the LiveData pointing to it. but the Alert shows that only currentUser.points is updated while userPoints stays the same at the initial value so an observer will never run. So what am I missing? How can I get this to work like I was expecting? Thanks