第一版,实现在非Compose作用域调用Compose函数:
@Composable
fun test() {val fun1 = @Composable() {rememberTextMeasurer()}val test1 = rememberTextMeasurer()val composer = currentComposerButton(onClick = {// 这是非Compose作用域,在此通过我们自定义的invokeCompose方法,执行Compose函数invokeCompose(composer, fun1)}) {}
}fun invokeCompose(composer: Composer, function: @Composable () -> Unit) {(function as ComposableLambda).invoke(composer, 100000)
}
第二版,支持返回值:
@Composable
fun test() {val fun1 = @Composable {// 这是Compose函数rememberTextMeasurer()}val composer = currentComposerButton(onClick = {// 这是非Compose作用域,在此通过我们自定义的invokeCompose方法,执行Compose函数val textMeasurer = invokeCompose(composer, fun1) // 类型是 Anyprintln("textMeasurer= $textMeasurer")}) {}
}fun invokeCompose(composer: Composer, function: @Composable () -> Any?): Any? {return (function as ComposableLambda).invoke(composer, 100000)
}
第三版,加入泛型,支持类型自动推导:
@Composable
fun test() {val fun1 = @Composable {// 这是Compose函数rememberTextMeasurer()}val composer = currentComposerButton(onClick = {// 这是非Compose作用域,在此通过我们自定义的invokeCompose方法,执行Compose函数val textMeasurer = invokeCompose(composer, fun1) // 类型是TextMeasurerprintln("textMeasurer= $textMeasurer")}) {}
}fun <T>invokeCompose(composer: Composer, function: @Composable () -> T?): T? {return (function as ComposableLambda).invoke(composer, 100000) as T
}
最终版,改为inline,提升性能:
@Composable
fun test() {val fun1 = @Composable {// 这是Compose函数rememberTextMeasurer()}val composer = currentComposerButton(onClick = {// 这是非Compose作用域,在此通过我们自定义的invokeCompose方法,执行Compose函数val textMeasurer = invokeCompose(composer, fun1) // 类型是TextMeasurerprintln("textMeasurer= $textMeasurer")}) {}
}inline fun <reified T>invokeCompose(composer: Composer,noinline function: @Composable () -> T?): T? {return (function as ComposableLambda).invoke(composer, 100000) as T
}
后续扩展,支持各个参数
@Composable
fun test() {// 含一个参数的Compose函数val fun1: @Composable (String) -> String = @Composable {it + "123"}val composer = currentComposerButton(onClick = {// 这是非Compose作用域,在此通过我们自定义的invokeCompose方法,执行Compose函数val textMeasurer = invokeCompose(composer, fun1, "arg1") // 类型是TextMeasurerprintln("textMeasurer= $textMeasurer")}) {}
}inline fun <reified T> invokeCompose(composer: Composer,noinline function: @Composable () -> T?
): T? {return (function as ComposableLambda).invoke(composer, 100000) as T
}inline fun <reified T, A> invokeCompose(composer: Composer,noinline function: @Composable (A) -> T?,p1: A
): T? {return (function as ComposableLambda).invoke(p1, composer, 100000) as T
}inline fun <reified T, A, B> invokeCompose(composer: Composer,noinline function: @Composable (A, B) -> T?,p1: A,p2: B
): T? {return (function as ComposableLambda).invoke(p1, p2, composer, 100000) as T...
}