I'm trying to collect callback flow from repository in viewmodel to save user Data. I have this two implementations:
CODE A)
private val _userState = MutableStateFlow<UserData?>(null)
val userState: StateFlow<UserData?> = _userState
init {
getUserData()
}
private fun getUserData() {
viewModelScope.launch {
user?.uid?.let {
userUseCases.getUserData(it).collect { response ->
when (response) {
is Loading -> {}
is Success -> { _userState.value = response.data }
is Failure -> userNewMessage(response.e?.message ?: CANT_LOAD_DATA)
}
userState.value?.let { userData ->
if (!userData.hasProfileCompleted())
userNewMessage("Falta completar el perfil")
}
}
Log.d("PROVES","LOG OUTSIDE COLLECT")
}
}
}
CODE B)
val userState2: StateFlow<UserData?> = flow {
user?.uid?.let {
userUseCases.getUserData(it).collect { dataResponse ->
when (dataResponse) {
is Loading -> Loading
is Success -> emit(dataResponse.data)
is Failure -> userNewMessage(dataResponse.e?.message ?: CANT_LOAD_DATA)
}
}
}
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = UserData()
)
Two implementations are working but I don't know what approach is better, what one should I implement? Besides this, the Log in the first implementation outside the collect, never logs. Why is this happening? Is the function stuck in the collect?
Thanks!