Jetpack Compose setContent 源碼分析
從何入手
先來了解一下Compose架構的分層設計
由上至下 | 說明 | 運用 |
---|---|---|
material | 提供了Material Design一套風格體系,包含主題系統、樣式化組件 | Button、AlertDialog等等 |
foundation | 相當于面向開發者的跟基層,包含完整的UI系統和實用布局 | LazyList、Row、Column等等 |
animation | 動畫層,包含平移、漸變、縮放等等,并且提供了方便開發者的動畫組件 | animate**AsState、Transition、Animatable、AnimatedVisibility等等 |
ui | ui相關的基礎功能,包括自定義布局、繪制、觸摸反饋等等 | ComposeView、Layout、LayoutNode等等 |
runtime | 最底層的概念模型,包括數據結構、狀態處理、數據同步等等 | mutableStateOf、remember等等 |
compiler | 基于Kotlin的編譯器插件 | 處理@Composable函數 |
了解完整體的分層設計,而要分析的setContent()
源碼是處于ui
層和runtime
層。
Compose版本號采用
1.0.1
代碼塊頂部注釋為類位置
先看一段Compose代碼
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 入口函數
setContent { // content 函數對象
Text("Hello Compose")
}
}
}
寫法很簡單,所以我們的目的也很簡單,就是看看setContent()
函數講Text("Hello Compose")
進行怎么樣的邏輯傳遞。為了之后的代碼跟隨能夠更加的清晰,后續講到入口函數對象
就等同于Text("Hello Compose")
ComponentActivity.setContent()
// androidx.activity.compose.ComponentActivity
public fun ComponentActivity.setContent(
parent: CompositionContext? = null,
content: @Composable () -> Unit
) {
// 1. 通過decorView找到ContentView,再獲得第一個ComposeView
val existingComposeView = window.decorView
.findViewById<ViewGroup>(android.R.id.content)
.getChildAt(0) as? ComposeView
// 2. 如果ComposeView為空則走初始化流程
if (existingComposeView != null) with(existingComposeView) {
setParentCompositionContext(parent)
setContent(content)
} else ComposeView(this).apply {
// 3. 初始化ComposeView肯定為空,則進入這邊
setParentCompositionContext(parent)
// 4. 把入口函數對象傳入ComposeView
setContent(content)
setOwners()
// 5. 把ComposeView設置進ContentView
setContentView(this, DefaultActivityContentLayoutParams)
}
}
從第一步可以了解到,原來在當前窗口的decorView中的android.R.id.content
中第0
個位置,會存在一個ComposeView,所以ComposeView結構圖可以理解成:
難道這個ComposeView肯定跟傳統的View/ViewGroup有關系嗎?遇事不決就看看Compose的繼承關系。
果真如此,也能驗證Compose架構的分層設計中上下關系,animation
、foundation
的工作也是在ComposeView中進行,另外還能延伸出一個問題,那是不是Compose和傳統View/ViewGroup能夠互相交互并且能在同一個activity混合開發?這個目前沒有研究過,就先略過了。。。
第二步的話,由于分析就是初始化狀態的流程且existingComposeView肯定為空,所以直接進入到第三步,傳遞了parent
到setParentCompositionContext
方法,按照案例的入口函數,
// 入口函數
setContent(parent = null) { // content 函數對象
Text("Hello Compose")
}
所以當前parent
為空,再看看方法里具體做了哪些。
// androidx.compose.ui.platform.AbstractComposeView
fun setParentCompositionContext(parent: CompositionContext?) {
parentContext = parent
}
只是賦值操作,目前parentContext
為空
第四步發現又調用了一個相同方法名的setContent
,在之后的分析還會出現一個類似的setContent
,每一個方法作用都是不一樣,那看看當前ComposeView.setContent(入口函數對象)
做了什么事情
// androidx.compose.ui.platform.ComposeView
class ComposeView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AbstractComposeView(context, attrs, defStyleAttr) {
private val content = mutableStateOf<(@Composable () -> Unit)?>(null)
@Suppress("RedundantVisibilityModifier")
protected override var shouldCreateCompositionOnAttachedToWindow: Boolean = false
private set
@Composable
override fun Content() {
content.value?.invoke()
}
fun setContent(content: @Composable () -> Unit) {
// 翻譯為 “應該在附加到窗口上創建合成”,做一個標記
shouldCreateCompositionOnAttachedToWindow = true
// 賦值操作
this.content.value = content
if (isAttachedToWindow) {
// 暫時不會進入
createComposition()
}
}
}
整個ComposeView的類結構
AbstractComposeView
abstract fun Content()
open val shouldCreateCompositionOnAttachedToWindow: Boolean
ComposeView
val content = mutableStateOf
fun setContent()
這樣一看理解ComposeView也很容易了,它只是做了一個預備動作,告訴AbstractComposeView有人(調用ComposeView.setContent()
后)把預備狀態修改成準備就緒啦(shouldCreateCompositionOnAttachedToWindow = true
),并且入口函數對象也存儲好了,等你來拿走處理了(Content()
= 入口函數對象)。
所以前兩句就是給AbstractComposeView
修改和準備需要的值。
而if
對于初始化分析來說,根本不會進入,因為當前的ComponentActivity.setContent
,還沒用執行到第五步setContentView
,所以isAttachedToWindow
肯定為false。
那再看第五步,setContentView
再熟悉不過了,添加到android.R.id.content
中。之后流程居然就沒了?第四步都準備就緒了,之后就沒有啟動邏輯了?
回想一下之前講的ComposeView的繼承關系,是View的子類,那setContentView
后ComposeView被附加到Window上后,會回調方法onAttachedToWindow()
。我們知道ComposeView的沒有這個方法的,在父類AbstractComposeView
中找到了該實現。
AbstractComposeView.onAttachedToWindow()
// androidx.compose.ui.platform.AbstractComposeView
override fun onAttachedToWindow() {
super.onAttachedToWindow()
previousAttachedWindowToken = windowToken
// ComposeView 修改后預備狀態
if (shouldCreateCompositionOnAttachedToWindow) {
// 真正啟動的地方
ensureCompositionCreated()
}
}
shouldCreateCompositionOnAttachedToWindow
這個值Compose.setContent()
已經修改為true
,所以直接看ensureCompositionCreated()
// androidx.compose.ui.platform.AbstractComposeView
private fun ensureCompositionCreated() {
// composition 初始化流程為空
if (composition == null) {
try {
creatingComposition = true
// 又來一個 setContent?
composition = setContent(resolveParentCompositionContext()) {
// 抽象方法
Content()
}
} finally {
creatingComposition = false
}
}
}
composition
還不確定是做什么的,先一步一步解析這個setContent
涉及的內容,看看方法的入參。
// androidx.compose.ui.platform.Wrapper_androidKt.class
internal fun ViewGroup.setContent(
parent: CompositionContext,
content: @Composable () -> Unit
): Composition {
...
parent
以目前的知識點也無法對它進行分析,而content
就是我們的入口函數對象。調用的Content()
抽象方法,方法的實現之前講過的,內部返回的就是ComposeView.content.value
為了了解parent
為何物,就要看看resolveParentCompositionContext()
方法。
resolveParentCompositionContext()
// androidx.compose.ui.platform.AbstractComposeView
private fun resolveParentCompositionContext() = parentContext
?: findViewTreeCompositionContext()?.also { cachedViewTreeCompositionContext = it }
?: cachedViewTreeCompositionContext
?: windowRecomposer.also { cachedViewTreeCompositionContext = it }
一大堆判空邏輯,那就挨個分析。
parentContext
: 就是ComponentActivity.setContent()
中第三步流程,并且還知道當前案例傳遞為空。
findViewTreeCompositionContext()
: 再看看源碼怎么尋找
// androidx.compose.ui.platform.WindowRecomposer_androidKt.class
fun View.findViewTreeCompositionContext(): CompositionContext? {
var found: CompositionContext? = compositionContext
if (found != null) return found
var parent: ViewParent? = parent
while (found == null && parent is View) {
found = parent.compositionContext
parent = parent.getParent()
}
return found
}
初始化流程默認compositionContext
為空,所以找上一層 parentVew, 然而整個while也是找不到需要的compositionContext
,所以findViewTreeCompositionContext
也會返回null。
cachedViewTreeCompositionContext
: 是跟隨上一個findViewTreeCompositionContext()
邏輯走的,上一個為空則cachedViewTreeCompositionContext
也會返回空。
windowRecomposer
: 看看源碼怎么尋找
// androidx.compose.ui.platform.WindowRecomposer_androidKt.class
internal val View.windowRecomposer: Recomposer
get() {
check(isAttachedToWindow) {
"Cannot locate windowRecomposer; View $this is not attached to a window"
}
// 擴展函數拿到 contentChild
val rootView = contentChild
return when (val rootParentRef = rootView.compositionContext) {
// 初始化流程為null
null -> WindowRecomposerPolicy.createAndInstallWindowRecomposer(rootView)
is Recomposer -> rootParentRef
else -> error("root viewTreeParentCompositionContext is not a Recomposer")
}
}
private val View.contentChild: View
get() {
var self: View = this
var parent: ViewParent? = self.parent
while (parent is View) {
// 拿到 ComposeView 后返回
if (parent.id == android.R.id.content) return self
self = parent
parent = self.parent
}
return self
}
contentChild
: View的擴展屬性,當前view的parentId等于android.R.id.content
時,會返回當前view。根據之前的知識(ComposeView結構圖)就可以得知,當前view肯定是初始化setContentView
傳入的ComposeView。
再根據當前為初始化流程,所以rootView.compositionContext
肯定也是為空,會進入WindowRecomposerPolicy.createAndInstallWindowRecomposer(rootView)
。看到這邊整個流程都是在尋找compositionContext,但是第一次進入頁面發現各種方法加擴展屬性尋找,都壓根找不到。從方法名create***
,其實就可以知道找不到我就去給你創建一個,并且這個方法還把rootView(ComposeView)傳入,在還沒有看createAndInstallWindowRecomposer(rootView)
,其實也可以猜出來,創建compositionContext是肯定的,并且還會把創建的compositionContext存儲到rootView(ComposeView)其中,之后再次尋找就有緩存可尋。
WindowRecomposerPolicy.createAndInstallWindowRecomposer(rootView)
刪減了部分代碼
// androidx.compose.ui.platform.WindowRecomposer_androidKt.class
fun interface WindowRecomposerFactory {
fun createRecomposer(windowRootView: View): Recomposer
companion object {
val LifecycleAware: WindowRecomposerFactory = WindowRecomposerFactory { rootView ->
// 4. createRecomposer() lambda調用createLifecycleAwareViewTreeRecomposer()
rootView.createLifecycleAwareViewTreeRecomposer()
}
}
}
private fun View.createLifecycleAwareViewTreeRecomposer(): Recomposer {
...
// 5. 創建 Recomposer
val recomposer = Recomposer(contextWithClock)
...
// 6. 返回 Recomposer
return recomposer
}
object WindowRecomposerPolicy {
private val factory = AtomicReference<WindowRecomposerFactory>(
// 2. 創建 WindowRecomposerFactory
WindowRecomposerFactory.LifecycleAware
)
...
// rootView = ComposeView
internal fun createAndInstallWindowRecomposer(rootView: View): Recomposer {
// 1. factory.get() 創建 WindowRecomposerFactory
// 3. createRecomposer(rootView) 調用 WindowRecomposerFactory.createRecomposer()
val newRecomposer = factory.get().createRecomposer(rootView)
// 7. compositionContext 賦值到 ComposeView Tag數組中
rootView.compositionContext = newRecomposer
...
// 8. 整個創建 compositionContext 結束
return newRecomposer
}
}
第一步到第三步是用工廠模式WindowRecomposerFactory
來創建Recomposer
。回想一下我們不是要拿CompositionContext對象的么?那這個Recomposer是何方神圣?
看一下繼承關系
對于Recomposer怎么理解,官方注解如下
/**
* The scheduler for performing recomposition and applying updates to one or more [Composition]s.
* 用于執行重組并將更新應用到一個或多個 [Composition] 的調度程序。
* 先了解定義,之后會分析Recomposer的內部運用
*/
所以第四步到第六步就是創建CompositionContext,并且返回賦值給對象newRecomposer。
第七步是newRecomposer賦值給rootView.compositionContext
, 看看賦值過程。
// androidx.compose.ui.platform.WindowRecomposer_androidKt.class
var View.compositionContext: CompositionContext?
get() = getTag(R.id.androidx_compose_ui_view_composition_context) as? CompositionContext
set(value) {
setTag(R.id.androidx_compose_ui_view_composition_context, value)
}
就是把CompositionContext添加到ComposeView的Tag數組,在Compose ui層的體系中,發現有很多類似的寫法,通過set/get Tag來存取值,且之后要分析的流程也有類似寫法。
第八步整個獲取CompositionContext流程終于結束了。
ViewGroup.setContent()
這個時候就要再貼一下之前的流程分析。
// androidx.compose.ui.platform.AbstractComposeView
private fun ensureCompositionCreated() {
// composition 初始化流程為空
if (composition == null) {
try {
creatingComposition = true
// 又來一個 setContent
composition = setContent(resolveParentCompositionContext()) {
// 抽象方法
Content()
}
} finally {
creatingComposition = false
}
}
}
// androidx.compose.ui.platform.Wrapper_androidKt.class
internal fun ViewGroup.setContent(
parent: CompositionContext, // Recomposer
content: @Composable () -> Unit // 入口函數對象
): Composition {
GlobalSnapshotManager.ensureStarted()
// 獲得 AndroidComposeView
val composeView =
if (childCount > 0) {
getChildAt(0) as? AndroidComposeView
} else {
removeAllViews(); null
} ?: AndroidComposeView(context).also {
// 添加到 ViewGroup(ComposeView)
addView(it.view, DefaultLayoutParams)
}
// 又來一個doSetContent
return doSetContent(composeView, parent, content)
}
ViewGroup.setContent
方法很簡單,獲得AndroidComposeView添加到ComposeView,然后再調用doSetContent()。
以初始化流程來看肯定會創建AndroidComposeView,AndroidComposeView的結構圖就可以理解為:
// // androidx.compose.ui.platform.Wrapper_androidKt.class
private fun doSetContent(
owner: AndroidComposeView,
parent: CompositionContext, // Recomposer
content: @Composable () -> Unit // 入口函數對象
): Composition {
...
// 創建 Composition
val original = Composition(UiApplier(owner.root), parent)
// 常見 WrappedComposition 并賦值到 AndroidComposeView 的Tag組數
val wrapped = owner.view.getTag(R.id.wrapped_composition_tag)
as? WrappedComposition
?: WrappedComposition(owner, original).also {
owner.view.setTag(R.id.wrapped_composition_tag, it)
}
// 又來一個setContent
wrapped.setContent(content)
return wrapped
}
Composition(UiApplier(owner.root), parent)
: 之前分析了parent,就是通過工廠模式創建的Recomposer,那要理解Composition還需要看看UiApplier是一個什么類?
UiApplier
internal class UiApplier(
root: LayoutNode
)
參數需要一個LayoutNode,那這個LayoutNode又是什么了?
先從目前的流程場景分析的的話,就直接查看傳遞的AndroidComposeView.root
// androidx.compose.ui.platform.AndroidComposeView
override val root = LayoutNode().also {
it.measurePolicy = RootMeasurePolicy
it.modifier = Modifier
.then(semanticsModifier)
.then(_focusManager.modifier)
.then(keyInputModifier)
}
原來AndroidComposeView有這個屬性對象,布局層次結構中的一個元素,用于compose UI構建,那又有一個問題了,當前是確定AndroidComposeView有這個元素,那入口函數對象也是用于compose UI構建,那它有沒有了?
答案是肯定有的,查看一下Text()
最底層實現源碼
// androidx.compose.foundation.text.CoreTextKt.class
internal fun CoreText(
...
) {
...
Layout(
content = if (inlineComposables.isEmpty()) {
{}
} else {
{ InlineChildren(text, inlineComposables) }
},
modifier = modifier
.then(controller.modifiers)
...
,
measurePolicy = controller.measurePolicy
)
...
}
// androidx.compose.ui.layout.LayoutKt.class
@Composable inline fun Layout(
content: @Composable () -> Unit,
modifier: Modifier = Modifier,
measurePolicy: MeasurePolicy
) {
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
ReusableComposeNode<ComposeUiNode, Applier<Any>>(
factory = ComposeUiNode.Constructor,
update = {
set(measurePolicy, ComposeUiNode.SetMeasurePolicy)
set(density, ComposeUiNode.SetDensity)
set(layoutDirection, ComposeUiNode.SetLayoutDirection)
},
skippableUpdate = materializerOf(modifier),
content = content
)
}
最終是調用了ReusableComposeNode<ComposeUiNode, Applier<Any>>
,而ComposeUiNode
就是LayoutNode的實現接口。
internal class LayoutNode : Measurable, Remeasurement, OwnerScope, LayoutInfo, ComposeUiNode
所以結合繼承關系可以把LayoutNode結構理解成:
對于UiApplier,就可以小結一下
UiApplier是一個視圖工具類,讓其他使用者能更方便的操作root: LayoutNode
。內部維護了一個stack = mutableListOf<T>()
代表類似上圖的視圖樹,當視圖樹插入、移除、移動等等都會更新stack。
那問題又來了,UiApplier是Composition的入參,究竟是哪個對象來操作UiApplier了?
Composition
// androidx.compose.runtime.CompositionKt.class
fun Composition(
applier: Applier<*>, // UiApplier
parent: CompositionContext // Recomposer
): Composition =
CompositionImpl(
parent,
applier
)
internal class CompositionImpl(
private val parent: CompositionContext, // Recomposer
private val applier: Applier<*>, // UiApplier
recomposeContext: CoroutineContext? = null
) : ControlledComposition {
...
// 保存所有視圖組合的信息(核心數據結構)
private val slotTable = SlotTable()
...
private val composer: ComposerImpl =
ComposerImpl(
applier = applier,
parentContext = parent,
slotTable = slotTable,
abandonSet = abandonSet,
changes = changes,
composition = this
).also {
parent.registerComposer(it)
}
...
}
SlotTable
是一個很大的話題,類似于 Gap Buffer (間隙緩沖區) ,技術有限這邊就不展開說了,官方可能覺得也很難理解,在知乎上說明了SlotTable
的執行模式。
所以可以說Composition是一個連接器,把視圖樹(UiApplier)和調度程序(Recomposer)連接到一起,當監聽到數據(比如mutableState)變化或者添加視圖等等,Recomposer會通過Composition通知SlotTable更新視圖組合信息、UiApplier更新視圖樹等等,在分析UiApplier的Text()
底層實現源碼中,最終是創建了ReusableComposeNode
,那在看看對應的源碼。
@Composable inline fun <T : Any, reified E : Applier<*>> ReusableComposeNode(
noinline factory: () -> T,
update: @DisallowComposableCalls Updater<T>.() -> Unit
) {
if (currentComposer.applier !is E) invalidApplier()
currentComposer.startReusableNode()
if (currentComposer.inserting) {
currentComposer.createNode { factory() }
} else {
currentComposer.useNode()
}
currentComposer.disableReusing()
Updater<T>(currentComposer).update()
currentComposer.enableReusing()
currentComposer.endNode()
}
currentComposer
就是Composition中的composer
調用startReusableNode()
就是操作SlotReader,而SlotReader其實就是SlotTable的讀取控制器,對應的SlotTable也有SlotWriter寫入控制器。
調用createNode()
就是操作UiApplier
WrappedComposition.setContent()
終于講到WrappedComposition.setContent()
,它是一個帶有處理生命周期的包裹,把AndroidComposeView和Composition包裹,當AndroidComposeView被附加到ComposeView后,會添加LifecycleEventObserver
,之后觸發生命周期Lifecycle.Event.ON_CREATE
,會先調用連接器Composition的setContent()
,再執行調度程序Recomposer的composeInitial()
,再調用連接器Composition的setContent() -> composeContent()
,再調用連接器中的帶有SlotTable的composer.composeContent()
,最終執行invokeComposable()
來組合我們的入口函數對象。
調用鏈看起來很懵逼,關鍵是要理解Composition、composer、CompositionContext(Recomposer)、UiApplier每個對象的關系、職責和工作的傳遞,最后再看看相關涉及的源碼。
// androidx.compose.ui.platform.WrappedComposition
private class WrappedComposition(
val owner: AndroidComposeView,
val original: Composition //
) : Composition, LifecycleEventObserver {
private var disposed = false
private var addedToLifecycle: Lifecycle? = null
private var lastContent: @Composable () -> Unit = {}
override fun setContent(content: @Composable () -> Unit) {
owner.setOnViewTreeOwnersAvailable {
if (!disposed) {
val lifecycle = it.lifecycleOwner.lifecycle
lastContent = content
if (addedToLifecycle == null) {
// 1. 初始化流程第一次會進入
addedToLifecycle = lifecycle
// 2. 設置生命周期監聽
lifecycle.addObserver(this)
} else if (lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
// 4. 調用連接器的setContent
original.setContent {
@Suppress("UNCHECKED_CAST")
val inspectionTable =
owner.getTag(R.id.inspection_slot_table_set) as?
MutableSet<CompositionData>
?: (owner.parent as? View)?.getTag(R.id.inspection_slot_table_set)
as? MutableSet<CompositionData>
if (inspectionTable != null) {
@OptIn(InternalComposeApi::class)
inspectionTable.add(currentComposer.compositionData)
currentComposer.collectParameterInformation()
}
LaunchedEffect(owner) { owner.keyboardVisibilityEventLoop() }
LaunchedEffect(owner) { owner.boundsUpdatesEventLoop() }
// 入口函數對象
CompositionLocalProvider(LocalInspectionTables provides inspectionTable) {
ProvideAndroidCompositionLocals(owner, content)
}
}
}
}
}
}
override fun dispose() {
if (!disposed) {
disposed = true
// 清空帶生命周期的包裹
owner.view.setTag(R.id.wrapped_composition_tag, null)
// 移除生命周期艦艇
addedToLifecycle?.removeObserver(this)
}
original.dispose()
}
override val hasInvalidations get() = original.hasInvalidations
override val isDisposed: Boolean get() = original.isDisposed
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_DESTROY) {
dispose()
} else if (event == Lifecycle.Event.ON_CREATE) {
if (!disposed) {
// 3. 重新執行
setContent(lastContent)
}
}
}
}
Composition -> original.setContent()
// androidx.compose.runtime.CompositionImpl
override fun setContent(content: @Composable () -> Unit) {
check(!disposed) { "The composition is disposed" }
this.composable = content
// parent = Recomposer = ComposeView.compositionContext
parent.composeInitial(this, composable)
}
Recomposer -> parent.composeInitial(this, composable)
// androidx.compose.runtime.Recomposer
internal override fun composeInitial(
composition: ControlledComposition, // Recomposer
content: @Composable () -> Unit // 入口函數對象
) {
val composerWasComposing = composition.isComposing
composing(composition, null) {
// 走到連接器
composition.composeContent(content)
}
...
}
composition.composeContent(content)
// androidx.compose.runtime.CompositionImpl
override fun composeContent(content: @Composable () -> Unit) {
synchronized(lock) {
drainPendingModificationsForCompositionLocked()
// 走到內部composer
composer.composeContent(takeInvalidations(), content)
}
}
composer.composeContent(takeInvalidations(), content)
// androidx.compose.runtime.ComposerImpl
internal fun composeContent(
invalidationsRequested: IdentityArrayMap<RecomposeScopeImpl, IdentityArraySet<Any>?>,
content: @Composable () -> Unit // 入口函數對象
) {
runtimeCheck(changes.isEmpty()) { "Expected applyChanges() to have been called" }
doCompose(invalidationsRequested, content)
}
private fun doCompose(
invalidationsRequested: IdentityArrayMap<RecomposeScopeImpl, IdentityArraySet<Any>?>,
content: (@Composable () -> Unit)? // 入口函數對象
) {
runtimeCheck(!isComposing) { "Reentrant composition is not supported" }
trace("Compose:recompose") {
snapshot = currentSnapshot()
invalidationsRequested.forEach { scope, set ->
val location = scope.anchor?.location ?: return
invalidations.add(Invalidation(scope, location, set))
}
invalidations.sortBy { it.location }
nodeIndex = 0
var complete = false
isComposing = true
try {
startRoot()
// Ignore reads of derivedStatOf recalculations
observeDerivedStateRecalculations(
start = {
childrenComposing++
},
done = {
childrenComposing--
},
) {
if (content != null) {
startGroup(invocationKey, invocation)
// 真正處理入口函數對象的地方
invokeComposable(this, content)
endGroup()
} else {
skipCurrentGroup()
}
}
endRoot()
complete = true
} finally {
isComposing = false
invalidations.clear()
providerUpdates.clear()
if (!complete) abortRoot()
}
}
}
startRoot()、endGroup() 是操作SlotTable
最后再看看invokeComposable
做了什么
internal fun invokeComposable(composer: Composer, composable: @Composable () -> Unit) {
@Suppress("UNCHECKED_CAST")
val realFn = composable as Function2<Composer, Int, Unit>
realFn(composer, 1)
}
原來最終把我們的入口函數對象強轉成Function2
,但是當要去查看Function2
是做什么的時候,沒辦法找到類。
原因是這邊是compiler(基于kotlin的編譯器插件)做的事情,它把我們的入口函數進行了修改,添加了一些參數,比如Int對應的就是groupId,所以才能強轉成功。拿官方的例子來說明一下就能明白了。
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(
text="Count: $count",
onPress={ count += 1 }
)
}
fun Counter($composer: Composer, groupId: Int) {
$composer.start(groupId)
var count by remember { mutableStateOf(0) }
Button(
text="Count: $count",
onPress={ count += 1 }
)
$composer.end()
}
小結
初次看setContent源碼,什么流程都記不住看不懂,只知道N個setContent跳來跳去,當把Composition、composer、CompositionContext(Recomposer)、UiApplier每個對象的關系、職責搞清楚之后,再對跳轉流程理清楚,就能發現具體的工作流程了。
所分析的setContent()
只是Compose Ui體系中的一小部分,發現分析完后,延伸出了更多的知識點,比如SlotTable工作的流程和時間復雜度、LayoutNode和AndroidComposeView相關的測量繪制觸摸反饋、mutableState刷新機制等等,還有分析過程中提出的一個問題Compose和傳統View/ViewGroup互相交互并且能在同一個activity混合開發嗎?