Best way to get Context in clickable modifier

Viewed 478

I have a piece of text that I want to call function X when clicked. I'm using the clickable modifier and calling function X in the onClick method to do this. However, function X uses Context.

To solve this problem, I'm using the approach outlined below:

@Composable
fun ClickableText() {
    val context = LocalContext.current
    Text("Click me!", Modifier.clickable { functionX(context) })
}

My question is, is there anything wrong with this type of approach? It seems to be working, but storing a local reference to LocalContext.current seems a bit hacky. If the Context ever changes in the time between the UI composition and the onClick method call, I'd assume this could cause some issues. Is there a better way to get Context in a non-composable callback function?

1 Answers

No, this is totally correct way of using LocalContext.current. It cannot change between recomposition and onClick.

Context is getting created before the composable view: usually it's your activity, and if you're using Hilt it may be a context wrapper, but it's getting created once before setContent, so if it'll change the whole compose view hierarchy will be rebuilt.

You shouldn't store it outside of the view, like in view models, but capturing it inside a composable is totally fine.

Related