Trying to understand TextField but running into a ...
# compose-desktop
m
Trying to understand TextField but running into a strange issue:
Copy code
class EditableTextComponent(private val file: File) {
    var contents = file.readText()
        private set

    private val _lock = Mutex()
    fun save() {
        if (_lock.tryLock()) {
            file.writeText(contents)
            _lock.unlock()
        }
    }

    private var _saveJob: Job? = null

    @OptIn(DelicateCoroutinesApi::class)
    fun notifyChange(newText: String) {
        _saveJob?.cancel()
        _saveJob = GlobalScope.launch(Dispatchers.IO) {
            delay(1000)
            contents = newText
            save()
        }
    }

    fun visualTransformation(annotated: AnnotatedString): TransformedText {
        print("visualTransformation")
        return TransformedText(
            text = annotated,
            offsetMapping = OffsetMapping.Identity
        )
    }
}

@Composable
fun EditableText(component: EditableTextComponent) {
    var value by remember { mutableStateOf(TextFieldValue(text = component.contents)) }

    TextField(
        value = value,
        onValueChange = {
            value = it
            component.notifyChange(it.text)
        },
        visualTransformation = component::visualTransformation,
        modifier = Modifier.fillMaxSize(),
    )
}
For some reason visualTransformation is called 3 times when it is first instantiated, and twice per click/keypress. How do I reduce this to just once?
z
You’re just trying to reduce recompositions, this doesn’t look like necessarily a text field-specific issue. I don’t know why you’re recomposing extra times - EditableTextComponent doesn’t look stable, so if its caller is recomposing then it will recompose as well.
m
The only thing changing in this is the text though, directly above this is the
@Preview fun App()
function