Today I faced the question of how to write the code correctly.
I have a Fragment in which I call the viewModel function viewModel.restorePassword()
.
There is a variable in viewModel:
private var _currentNumberPhone = MutableStateFlow<String>("")
val currentNumberPhone: StateFlow<String> = _currentNumberPhone.asStateFlow()
1) First function
fun restorePassword() {
viewModelScope.launch {
currentNumberPhone.collect { phone ->
restorePasswordByPhone(phone)
}
}
}
2) Second function
fun restorePassword() {
restorePasswordByPhone(currentNumberPhone.value)
}
In restorePasswordByPhone()
there is a call to the network, via Coroutine. It's nothing special. And I have a question, what is the right way to handle StateFlow variable through subscription and collect or regular currentNumberPhone.value
? The thing is, I don't need to observe all the time. When I call the restorePassword() method, I need to pass the currentNumberPhone value and that's it.
I don't know what the differences are!