为了方便跟踪代码,我来给代码设置点跟踪器 (别搞丢了)😜 下面的代码中 modifier 参数达到的位置我会用📍 标记, measurePolicy 到达的位置用 📌 标记
Layout.kt → Layout 函数源码
@Composable inline fun Layout(
content: @Composable () -> Unit,
modifier: Modifier = Modifier,
measurePolicy: MeasurePolicy
) {
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
ReusableComposeNode<ComposeUiNode, Applier>(
factory = ComposeUiNode.Constructor,
update = {
set(measurePolicy, ComposeUiNode.SetMeasurePolicy) // 👈 📌 measurePolicy 在这
set(density, ComposeUiNode.SetDensity)
set(layoutDirection, ComposeUiNode.SetLayoutDirection)
},
skippableUpdate = materializerOf(modifier), // 👈 📍 modifier 在这
content = content
)
}
从上面源码可以看出,Layout 函数体中没有做什么处理,核心内容就是调用 ReusableComposeNode 函数。
@Composable 注解的函数建议首字母大写已区分普通函数,看代码的时候总觉的 ReusableComposeNode 是个类,点进去发现它是个 Composable 函数 😂 。
Composables.kt → ReusableComposeNode 函数
inline fun <T, reified E : Applier<*>> ReusableComposeNode(
noinline factory: () -> T,
update: @DisallowComposableCalls Updater.() -> Unit,
noinline skippableUpdate: @Composable SkippableUpdater.() -> Unit,
content: @Composable () -> Unit
) {
if (currentComposer.applier !is E) invalidApplier()
currentComposer.startNode()
if (currentComposer.inserting) {
currentComposer.createNode(factory)
} else {
currentComposer.useNode()
}
//执行update函数
Updater(currentComposer).update() // 👈 📌 measurePolicy 在这
//执行skippableUpdate函数
SkippableUpdater(currentComposer).skippableUpdate() // 👈 📍 modifier 在这函数中
currentComposer.startReplaceableGroup(0x7ab4aae9)
content()
currentComposer.endReplaceableGroup()
currentComposer.endNode()
}
先只看和 modifier 有关的,即 SkippableUpdater<T>(currentComposer).skippableUpdate()
这句话,其他的先不看。
这里函数的参数都是函数参数类型,如果 Kotlin 不太熟悉的,可能看着比较晕 😵 ,下面为了方便分析一下,就把代码给它摊平了。
这里的 “代码给它摊平了” 是指去掉函数回调和一层层的调用,直接写到一起,避免函数跳来跳去,方便解释。下文中提到的摊平都是这个意思。
下面我就试着把它摊平看看。
//源代码
SkippableUpdater(currentComposer).skippableUpdate()
//0️⃣ 根据 ComposeNode 传入参数知
skippableUpdate=materializerOf(modifier) // 👈 📍 modifier
//1️⃣ materializerOf 函数返回值就是函数类型 SkippableUpdater.() -> Unit
internal fun materializerOf(
modifier: Modifier
): @Composable SkippableUpdater.() -> Unit = {
// 📍 这里只是对 modifier链中存在的 ComposedModifier 进行处理一下,返回值还是 Modifier
val materialized = currentComposer.materialize(modifier)
update { set(materialized, ComposeUiNode.SetModifier) } // 👈 📍 modifier
}
//结合代码 0️⃣ 和代码 1️⃣ 可知 SkippableUpdater(currentComposer).skippableUpdate()
//<=> 等价于代码如下
val skippableUpdater=SkippableUpdater(currentComposer)