I'm getting user data from Firestore using MVVM. In the repository class I use:
fun getUserData() = flow {
auth.currentUser?.apply {
val user = ref.document(uid).get().await().toObject(User::class.java)
user?.let {
emit(Success(user))
}
}
}. catch { error ->
error.message?.let { message ->
emit(Failure(message))
}
}
This method is called from the ViewModel class:
fun getUser() = repo.getUserData()
And in the activity class I use:
private fun getUser() {
lifecycleScope.launch {
viewModel.getUser().collect { data ->
when(data) {
is Success -> textView.text = data.user.name
is Failure -> print(data.message)
}
}
}
}
To display the name in the TextView. The code works fine. But is this the correct way if doing things? Or is it more correct to collect the data in the ViewModel class?
Any room for improvement? Thanks