I'm new to using Flows. I have a situation where I need to wait on userLoginStatusChangedFlow to collect before calling readProfileFromFirestore() (which also collects a Flow). The first checks that the user is logged into Firebase Auth, while the second downloads the user's profile information from Firestore. The code I have works, but I'm not sure if I'm doing it in the intended way.
Question: Is it standard practice to "chain" Flows like this? Would you do it any differently?
init {
viewModelScope.launch {
repository.userLoginStatusChangedFlow.collect { userLoggedIn: Boolean? ->
if (userLoggedIn == true) {
launch {
readProfileFromFirestore()
}
} else {
navigateToLoginFragment()
}
}
}
}
The readProfileFromFirestore() method that gets called above:
// Download profile from Firestore and update the repository's cached profile.
private suspend fun readProfileFromFirestore() {
repository.readProfileFromFirestoreFlow().collect { state ->
when (state) {
is State.Success -> {
val profile: Models.Profile? = state.data
if (profile != null && repository.isProfileComplete(profile)) {
repository.updateCachedProfile(profile)
navigateToExploreFragment()
} else {
navigateToAuthenticationFragment()
}
}
is State.Failed -> {
// Error occurred while getting profile, so just inform user and go to LoginFragment.
displayErrorToast(state.throwable.message ?: "Failed to get profile")
navigateToAuthenticationFragment()
}
is State.Loading -> return@collect
}
}
}