0

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

Joan P.
  • 2,368
  • 6
  • 30
  • 63
  • 1
    This shouldn’t be a Flow in the first place because you are only retrieving one thing. It should be a suspend function that returns that one thing. – Tenfour04 Sep 01 '21 at 11:28
  • @Tenfour04 Good point. Let's say I'm listening for real-time changes and use flow. Does it make sense to collect the data in the activity or in the ViewModel? – Joan P. Sep 01 '21 at 12:12
  • 1
    I come from the _other question_. I would collect the data in the VM, so the collected data survives configuration changes. The scope of the view (activity) should not drive all your data flow. The VM should, as it has the ability to live a bit longer. StateFlow is good (in this last step) because it has the ability to tell the VM, we no longer need this, so don't waste resources. – Martin Marconcini Sep 01 '21 at 14:00
  • @MartinMarconcini Thanks Martin. Can you write an answer for that? – Joan P. Sep 02 '21 at 06:51

1 Answers1

2

My personal opinion is that data should be collected in the VM so it survives configuration changes.

The scope of the view (activity/fragment) should not drive your data flow.

The VM will outlive activities and fragments during configuration changes, so all the data you have collected and transformed, will still be there (or in progress if it's still being obtained).

StateFlow is good (in this last step) because it has the ability to tell the VM: This is no longer needed, don't waste resources.

But I haven't yet used StateFlow in production code so there's that.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144