0

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!

1 Answers1

1

When you call collect, the code in the lambda is run every time the value in the StateFlow changes, forever until the CoroutineScope or your collection Job is cancelled. If you never need to do that, you don't need a StateFlow at all.

If you find that every time you change the value in the StateFlow that you always want to call this restore passwords function, then it makes sense to use collect(). If the restore passwords function is just updating another Flow, then you may not even need to expose this flow publicly at all or collect it, but rather simply use it as the basis of your password flow (via stateIn).

If you're using a Flow, it is rare to need value, except you might use the current value to determine what to do when you're deciding what new value to put in it. Aside from that, there could be some special cases where you're using the value for a one-off task in addition to whatever you're doing when you collect it.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154