'Can I store a composable function in a variable?
In Kotlin, function is a first-class citizen. We can store a function in a variable as below
val functionVariable: () -> Unit = ::myFunction
fun myFunction() { }
However, for @Composable
function, how can I do so?
If I did the below, it will cry foul i.e. org.jetbrains.kotlin.diagnostics.SimpleDiagnostic@e93b05f8 (error: could not render message)
val functionVariable: () -> Unit = ::myFunction
@Composable
fun myFunction() { }
Is there a way to store composable function as a variable?
Solution 1:[1]
Composable function reference is not yet supported (and that's what the error message actually is). Besides, @Composable
annotation is part of the function signature because it adds some parameters to the function. So you need to use val functionVariable: @Composable () -> Unit = { myFunction() }
.
Solution 2:[2]
You can declare a composable function variable, like:
var functionVariable: @Composable () -> Unit = {}
Later you can reassign it (essentially redefining it) like:
functionVariable = { myFunction1() }
or
functionVariable = { myFunction2() }
But if you have functionVariable already planted in your larger Composable, the reassignment likely won't trigger recomposation. What I do is declare a state variable like:
var functionAssigned by mutableStateOf(0)
And in you larger Composable where you plant functionVariable, do:
if (functionAssigned >= 0) functionVariable()
And whenever you want to reassign the variable, do:
functionVariable = { myFunction2() }
functionAssigned++
That will trigger needed recomposation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | H.D. |
Solution 2 | LeoXJ |