https://kotlinlang.org logo
Title
j

Jose Carlos Hernandez

08/11/2022, 6:21 PM
Hi guys, I’m trying to validate a TextField with Jetpack Compose using StateFlow on a ViewModel I saw an example that looks like this:
val isButtonEnabled: StateFlow<Boolean> =
        combine(isLoading, login, password) { isLoading, login, password ->
            isLoading.not() && login.isNotBlank() && password.isNotBlank()
        }.stateIn(viewModelScope, SharingStarted.Eagerly, false)
But I only have 1 field instead to validate so I try to put it like this
val isContinueEnable: StateFlow<Boolean> = MutableStateFlow(login.value.isNotBlank())
        .stateIn(viewModelScope, SharingStarted.Eagerly, false)
but when I start typing on the TextField it doesn’t change de value to
true
so is there a method similar to
combine
to get
Flow
but just with one element?
l

Landry Norris

08/11/2022, 6:33 PM
I would use
login.map { it.isNotBlank() }
instead of a MutableStateFlow. You are currently getting the initial value of login.isNotBlank and using that to initialize a MutableStateFlow, but you never mutate the flow you create.
You can think of combine as a way to map multiple flows at once.
j

Jose Carlos Hernandez

08/11/2022, 6:36 PM
nice! that was exactly what I wanted but didn’t knew the
map
function… thank you man!