本篇過(guò)于簡(jiǎn)陋圣猎,學(xué)藝不精禀梳,請(qǐng)移步第二版:Jetpack Compose生命周期監(jiān)聽(tīng)(第二版)
事情是這樣的
本人學(xué)習(xí)Compose有兩周多了,目前已經(jīng)著手重構(gòu)項(xiàng)目上的UI,因?yàn)轫?xiàng)目體積龐大笔刹,要把所有Activity段時(shí)間內(nèi)替換成只有一個(gè)Compose的方式肯定不現(xiàn)實(shí),目前就從替換xml布局開(kāi)始冬耿。說(shuō)實(shí)話舌菜,用了這么久的View,感覺(jué)有些坑挺多淆党,View從反射到繪制需要的時(shí)間還是挺長(zhǎng)的酷师,經(jīng)常會(huì)遇到因?yàn)槔L制延遲導(dǎo)致的各式各樣的問(wèn)題,遂決定逐步遷移到Compose上面來(lái)染乌。
使用場(chǎng)景
搜索全網(wǎng)山孔,各式各樣Compose相關(guān)的文章很多,也很詳細(xì)荷憋,根據(jù)現(xiàn)有的資料台颠,很難查到關(guān)于Activity聲明周期監(jiān)聽(tīng)的文章,因?yàn)榇蠖鄶?shù)人都是使用單個(gè)Activity + Navigation 的形式勒庄。舉個(gè)例子串前,在某些場(chǎng)景下,當(dāng)用戶進(jìn)入新的Activity時(shí)实蔽,需要默認(rèn)去請(qǐng)求頁(yè)面所需的數(shù)據(jù)荡碾,如果在Compose中直接調(diào)用,肯定是不行的局装,根據(jù)Compose刷新機(jī)制坛吁,接口會(huì)被瘋狂的調(diào)用,顯然是不合理的铐尚,這里我就自己歸納出了一個(gè)方法作為過(guò)渡拨脉。
觀察者
自制生命周期觀察者,其中 DefaultLifecycleObserver
來(lái)自 androidx.lifecycle.DefaultLifecycleObserver
class ComposeLifecycleObserver : DefaultLifecycleObserver {
private var create: (() -> Unit)? = null
private var start: (() -> Unit)? = null
private var resume: (() -> Unit)? = null
private var pause: (() -> Unit)? = null
private var stop: (() -> Unit)? = null
private var destroy: (() -> Unit)? = null
fun onLifeCreate(scope: () -> Unit) {
this.create = scope
}
fun onLifeStart(scope: () -> Unit) {
this.start = scope
}
fun onLifeResume(scope: () -> Unit) {
resume = scope
}
fun onLifePause(scope: () -> Unit) {
this.pause = scope
}
fun onLifeStop(scope: () -> Unit) {
this.stop = scope
}
fun onLifeDestroy(scope: () -> Unit) {
this.destroy = scope
}
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
create?.invoke()
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
start?.invoke()
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
resume?.invoke()
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
pause?.invoke()
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
stop?.invoke()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
destroy?.invoke()
}
}
方法
在 Composable
中監(jiān)聽(tīng)組合狀態(tài)宣增,一旦組合被釋放玫膀,就移除聲明周期觀察
@Composable
fun rememberLifecycle(): ComposeLifecycleObserver {
val observer = ComposeLifecycleObserver()
val owner = LocalLifecycleOwner.current
DisposableEffect(key1 = "lifecycle", effect = {
owner.lifecycle.addObserver(observer)
onDispose {
owner.lifecycle.removeObserver(observer)
}
})
val ctx = LocalContext.current
return remember(ctx) { observer }
}
使用
在不同的聲明周期里做要做的事情即可
@Composable
fun TestScreen(){
val life = rememberLifecycle()
life.onLifeCreate { TODO() }
life.onLifeStart { TODO() }
life.onLifeResume { TODO() }
life.onLifePause { TODO() }
life.onLifeStop { TODO() }
life.onLifeDestroy { TODO() }
}
最后
非科班跨行程序員,如有錯(cuò)誤歡迎批評(píng)爹脾。