我有LoginViewModel,其中包含邮箱和密码的合成状态支持字段.我想创建一个StateFlow来启用/禁用登录按钮.我用combine
和snapshotFlow
和stateIn
来表示.但问题是,只有initialvalue
次被释放.当composition backed状态发生变化时,snapshotFlow看起来不会被触发.这是我期待的还是我错过了什么?
@Test
fun testStateFlow() = runTest {
var emailState by mutableStateOf("")
var passwordState by mutableStateOf("")
val allInputValid: StateFlow<Boolean> = combine(
snapshotFlow { emailState },
snapshotFlow { passwordState }
) { emailValue, passwordValue ->
emailValue.isNotEmpty() && passwordValue.isNotEmpty()
}.stateIn(
CoroutineScope(UnconfinedTestDispatcher(testScheduler)),
SharingStarted.WhileSubscribed(5000),
false
)
val test = mutableListOf<String>()
val job = launch {
allInputValid.collect {
test.add("Value emitted: $it")
println(it)
}
}
advanceUntilIdle()
emailState = "test_email"
passwordState = "test_password"
advanceUntilIdle()
println(test)
job.cancel()
}