martmists
10/12/2023, 10:29 PMclass 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?Zach Klippenstein (he/him) [MOD]
10/13/2023, 12:52 PMmartmists
10/13/2023, 2:44 PM@Preview fun App()
function