Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how make delay in compose function

I make a simple field with validation:

@Composable
private fun MyField(value:String) {
    OutlinedTextField(
        value = value,
        onValueChange = {
        { value = it },
        modifier = Modifier,
        label = {
            Text(text = stringResource(id = R.string.field))
        },
        isError = value.length < 5
    )
    if (value.length < 5) {
        Text(
            text = stringResource(R.string.field_nor_valid),
            color = Color.Black
        )
    }
}

I want to change field color during inputting if it is <5. But I want change it through 3 second.That is, I want to validate not immediately, while the user types, but after some time. How can I do that?

like image 617
Monica Avatar asked Aug 20 '26 23:08

Monica


1 Answers

To delay the validation by 3 seconds after the user types in a Jetpack Compose TextField, you can utilize the LaunchedEffect composable in tandem with kotlinx.coroutines.delay.

@Composable
private fun MyField(value: MutableState<String>) {
    var isError by remember { mutableStateOf(false) }

    OutlinedTextField(
        value = value.value,
        onValueChange = {
            value.value = it
            LaunchedEffect(it) {
                delay(3000)  // the delay of 3 seconds
                isError = it.length < 5
            }
        },
        modifier = Modifier,
        label = {
            Text(text = stringResource(id = R.string.field))
        },
        isError = isError
    )
    if (isError) {
        Text(
            text = stringResource(R.string.field_not_valid),
            color = Color.Black
        )
    }
}
like image 193
Sternisic Avatar answered Aug 22 '26 12:08

Sternisic