https://kotlinlang.org logo
#compose
Title
# compose
m

mohamed rejeb

03/17/2024, 10:23 PM
Can we run Compose
TextMeasurer
measure
method on a background thread? I tried running it inside a
LaunchedEffect
on
Dispatchers.Default
but it keeps blocking the main thread.
🆙 1
I'm measuring the font size so the text fits all available space. And I'm hiding the text when I'm measuring and I show it after.
h

Halil Ozercan

03/18/2024, 2:48 PM
Copy code
@Composable
fun DrawTextMeasure() {
    val textMeasurer = rememberTextMeasurer()
    val textLayoutResult by produceState<TextLayoutResult?>(initialValue = null) {
        withContext(Dispatchers.Default) {
            println("TextMeasurer; running thread ${Thread.currentThread().id}")
            delay(5000)
            println("TextMeasurer; calculating thread ${Thread.currentThread().id}")
            value = textMeasurer.measure("Hello, World!")
        }
    }

    Canvas(Modifier.fillMaxWidth().height(100.dp)) {
        val padding = 16.dp.toPx()
        textLayoutResult?.let { drawText(it, topLeft = Offset(padding, padding)) }
    }
}
Something like this seems to work without blocking the main thread.
produceState
is just a fancy
LaunchedEffect
wrapper.
thank you color 2
5 Views